org.apache.commons.io.FileUtils.openOutputStream()方法的使用及代码示例

x33g5p2x  于2022-01-18 转载在 其他  
字(13.1k)|赞(0)|评价(0)|浏览(425)

本文整理了Java中org.apache.commons.io.FileUtils.openOutputStream()方法的一些代码示例,展示了FileUtils.openOutputStream()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。FileUtils.openOutputStream()方法的具体详情如下:
包路径:org.apache.commons.io.FileUtils
类名称:FileUtils
方法名:openOutputStream

FileUtils.openOutputStream介绍

[英]Opens a FileOutputStream for the specified file, checking and creating the parent directory if it does not exist.

At the end of the method either the stream will be successfully opened, or an exception will have been thrown.

The parent directory will be created if it does not exist. The file will be created if it does not exist. An exception is thrown if the file object exists but is a directory. An exception is thrown if the file exists but cannot be written to. An exception is thrown if the parent directory cannot be created.
[中]打开指定文件的FileOutputStream,检查并创建父目录(如果不存在)。
在方法结束时,要么成功打开流,要么抛出异常。
如果父目录不存在,将创建它。如果文件不存在,将创建该文件。如果文件对象存在但为目录,则引发异常。如果文件存在但无法写入,将引发异常。如果无法创建父目录,将引发异常。

代码示例

代码示例来源:origin: commons-io/commons-io

/**
 * Opens a {@link FileOutputStream} for the specified file, checking and
 * creating the parent directory if it does not exist.
 * <p>
 * At the end of the method either the stream will be successfully opened,
 * or an exception will have been thrown.
 * <p>
 * The parent directory will be created if it does not exist.
 * The file will be created if it does not exist.
 * An exception is thrown if the file object exists but is a directory.
 * An exception is thrown if the file exists but cannot be written to.
 * An exception is thrown if the parent directory cannot be created.
 *
 * @param file the file to open for output, must not be {@code null}
 * @return a new {@link FileOutputStream} for the specified file
 * @throws IOException if the file object is a directory
 * @throws IOException if the file cannot be written to
 * @throws IOException if a parent directory needs creating but that fails
 * @since 1.3
 */
public static FileOutputStream openOutputStream(final File file) throws IOException {
  return openOutputStream(file, false);
}

代码示例来源:origin: commons-io/commons-io

/**
 * Writes a String to a file creating the file if it does not exist.
 *
 * @param file     the file to write
 * @param data     the content to write to the file
 * @param encoding the encoding to use, {@code null} means platform default
 * @param append   if {@code true}, then the String will be added to the
 *                 end of the file rather than overwriting
 * @throws IOException in case of an I/O error
 * @since 2.3
 */
public static void writeStringToFile(final File file, final String data, final Charset encoding,
                   final boolean append) throws IOException {
  try (OutputStream out = openOutputStream(file, append)) {
    IOUtils.write(data, out, encoding);
  }
}

代码示例来源:origin: commons-io/commons-io

/**
 * Writes {@code len} bytes from the specified byte array starting
 * at offset {@code off} to a file, creating the file if it does
 * not exist.
 *
 * @param file   the file to write to
 * @param data   the content to write to the file
 * @param off    the start offset in the data
 * @param len    the number of bytes to write
 * @param append if {@code true}, then bytes will be added to the
 *               end of the file rather than overwriting
 * @throws IOException in case of an I/O error
 * @since 2.5
 */
public static void writeByteArrayToFile(final File file, final byte[] data, final int off, final int len,
                    final boolean append) throws IOException {
  try (OutputStream out = openOutputStream(file, append)) {
    out.write(data, off, len);
  }
}

代码示例来源:origin: commons-io/commons-io

/**
 * Copies bytes from an {@link InputStream} <code>source</code> to a file
 * <code>destination</code>. The directories up to <code>destination</code>
 * will be created if they don't already exist. <code>destination</code>
 * will be overwritten if it already exists.
 * The {@code source} stream is left open, e.g. for use with {@link java.util.zip.ZipInputStream ZipInputStream}.
 * See {@link #copyInputStreamToFile(InputStream, File)} for a method that closes the input stream.
 *
 * @param source      the <code>InputStream</code> to copy bytes from, must not be {@code null}
 * @param destination the non-directory <code>File</code> to write bytes to
 *                    (possibly overwriting), must not be {@code null}
 * @throws IOException if <code>destination</code> is a directory
 * @throws IOException if <code>destination</code> cannot be written
 * @throws IOException if <code>destination</code> needs creating but can't be
 * @throws IOException if an IO error occurs during copying
 * @since 2.5
 */
public static void copyToFile(final InputStream source, final File destination) throws IOException {
  try (InputStream in = source;
     OutputStream out = openOutputStream(destination)) {
    IOUtils.copy(in, out);
  }
}

代码示例来源:origin: commons-io/commons-io

/**
 * Implements the same behaviour as the "touch" utility on Unix. It creates
 * a new file with size 0 or, if the file exists already, it is opened and
 * closed without modifying it, but updating the file date and time.
 * <p>
 * NOTE: As from v1.3, this method throws an IOException if the last
 * modified date of the file cannot be set. Also, as from v1.3 this method
 * creates parent directories if they do not exist.
 *
 * @param file the File to touch
 * @throws IOException If an I/O problem occurs
 */
public static void touch(final File file) throws IOException {
  if (!file.exists()) {
    openOutputStream(file).close();
  }
  final boolean success = file.setLastModified(System.currentTimeMillis());
  if (!success) {
    throw new IOException("Unable to set the last modification time for " + file);
  }
}

代码示例来源:origin: commons-io/commons-io

/**
 * Writes the <code>toString()</code> value of each item in a collection to
 * the specified <code>File</code> line by line.
 * The specified character encoding and the line ending will be used.
 *
 * @param file       the file to write to
 * @param encoding   the encoding to use, {@code null} means platform default
 * @param lines      the lines to write, {@code null} entries produce blank lines
 * @param lineEnding the line separator to use, {@code null} is system default
 * @param append     if {@code true}, then the lines will be added to the
 *                   end of the file rather than overwriting
 * @throws IOException                          in case of an I/O error
 * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM
 * @since 2.1
 */
public static void writeLines(final File file, final String encoding, final Collection<?> lines,
               final String lineEnding, final boolean append) throws IOException {
  try (OutputStream out = new BufferedOutputStream(openOutputStream(file, append))) {
    IOUtils.writeLines(lines, lineEnding, out, encoding);
  }
}

代码示例来源:origin: SonarSource/sonarqube

private void backup(DbSession dbSession, QProfileDto profile, File backupFile) {
 try (Writer writer = new OutputStreamWriter(FileUtils.openOutputStream(backupFile), UTF_8)) {
  backuper.backup(dbSession, profile, writer);
 } catch (IOException e) {
  throw new IllegalStateException("Fail to open temporary backup file: " + backupFile, e);
 }
}

代码示例来源:origin: SonarSource/sonarqube

public static void zipDir(File dir, File zip) throws IOException {
 try (OutputStream out = FileUtils.openOutputStream(zip);
  ZipOutputStream zout = new ZipOutputStream(out)) {
  doZipDir(dir, zout);
 }
}

代码示例来源:origin: SonarSource/sonarqube

private File unpack200(String pluginKey, File compressedFile) {
 LOGGER.debug("Unpacking plugin {}", pluginKey);
 File jar = newTempFile();
 try (InputStream input = new GZIPInputStream(new BufferedInputStream(FileUtils.openInputStream(compressedFile)));
    JarOutputStream output = new JarOutputStream(new BufferedOutputStream(FileUtils.openOutputStream(jar)))) {
  Pack200.newUnpacker().unpack(input, output);
 } catch (IOException e) {
  throw new IllegalStateException(format("Fail to download plugin [%s]. Pack200 error.", pluginKey), e);
 }
 return jar;
}

代码示例来源:origin: commons-io/commons-io

@Test
public void test_openOutputStream_notExists() throws Exception {
  final File file = new File(getTestDirectory(), "a/test.txt");
  try (FileOutputStream out = FileUtils.openOutputStream(file)) {
    out.write(0);
  }
  assertTrue(file.exists());
}

代码示例来源:origin: commons-io/commons-io

void openOutputStream_noParent(final boolean createFile) throws Exception {
  final File file = new File("test.txt");
  assertNull(file.getParentFile());
  try {
    if (createFile) {
      TestUtils.createLineBasedFile(file, new String[]{"Hello"});
    }
    try (FileOutputStream out = FileUtils.openOutputStream(file)) {
      out.write(0);
    }
    assertTrue(file.exists());
  } finally {
    if (!file.delete()) {
      file.deleteOnExit();
    }
  }
}

代码示例来源:origin: commons-io/commons-io

@Test
public void test_openOutputStream_existsButIsDirectory() throws Exception {
  final File directory = new File(getTestDirectory(), "subdir");
  directory.mkdirs();
  try (FileOutputStream out = FileUtils.openOutputStream(directory)) {
    fail();
  } catch (final IOException ioe) {
    // expected
  }
}

代码示例来源:origin: SonarSource/sonarqube

private void enqueueDownload(String pluginKey, String pluginHash) throws IOException {
 File jar = temp.newFile();
 Manifest manifest = new Manifest();
 manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
 manifest.getMainAttributes().putValue("Plugin-Key", pluginKey);
 try (JarOutputStream output = new JarOutputStream(FileUtils.openOutputStream(jar), manifest)) {
 }
 doReturn(Optional.of(jar)).when(pluginFiles).get(argThat(p -> pluginKey.equals(p.key) && pluginHash.equals(p.hash)));
}

代码示例来源:origin: commons-io/commons-io

@Test
public void test_openOutputStream_exists() throws Exception {
  final File file = new File(getTestDirectory(), "test.txt");
  TestUtils.createLineBasedFile(file, new String[]{"Hello"});
  try (FileOutputStream out = FileUtils.openOutputStream(file)) {
    out.write(0);
  }
  assertTrue(file.exists());
}

代码示例来源:origin: commons-io/commons-io

@Test
public void test_openOutputStream_notExistsCannotCreate() throws Exception {
  // according to Wikipedia, most filing systems have a 256 limit on filename
  final String longStr =
      "abcdevwxyzabcdevwxyzabcdevwxyzabcdevwxyzabcdevwxyz" +
          "abcdevwxyzabcdevwxyzabcdevwxyzabcdevwxyzabcdevwxyz" +
          "abcdevwxyzabcdevwxyzabcdevwxyzabcdevwxyzabcdevwxyz" +
          "abcdevwxyzabcdevwxyzabcdevwxyzabcdevwxyzabcdevwxyz" +
          "abcdevwxyzabcdevwxyzabcdevwxyzabcdevwxyzabcdevwxyz" +
          "abcdevwxyzabcdevwxyzabcdevwxyzabcdevwxyzabcdevwxyz";  // 300 chars
  final File file = new File(getTestDirectory(), "a/" + longStr + "/test.txt");
  try (FileOutputStream out = FileUtils.openOutputStream(file)) {
    fail();
  } catch (final IOException ioe) {
    // expected
  }
}

代码示例来源:origin: apache/storm

@Test
  public void testEmptyState() throws IOException {
    TmpPath tmp_dir = new TmpPath();
    String dir = tmp_dir.getPath();
    LocalState ls = new LocalState(dir, true);
    GlobalStreamId gs_a = new GlobalStreamId("a", "a");
    FileOutputStream data = FileUtils.openOutputStream(new File(dir, "12345"));
    FileOutputStream version = FileUtils.openOutputStream(new File(dir, "12345.version"));
    Assert.assertNull(ls.get("c"));
    ls.put("a", gs_a);
    Assert.assertEquals(gs_a, ls.get("a"));

  }
}

代码示例来源:origin: commons-io/commons-io

dir.mkdirs();
final OutputStream tarFileAStream = FileUtils.openOutputStream(tarFileA);
TestUtils.generateTestData(tarFileAStream, tarMagicNumberOffset);
IOUtils.write(tarMagicNumber, tarFileAStream, StandardCharsets.UTF_8);

代码示例来源:origin: commons-io/commons-io

dir.mkdirs();
final OutputStream tarFileAStream = FileUtils.openOutputStream(tarFileA);
TestUtils.generateTestData(tarFileAStream, tarMagicNumberOffset);
IOUtils.write(tarMagicNumber, tarFileAStream);

代码示例来源:origin: commons-io/commons-io

@Test
public void testMagicNumberFileFilterString() throws Exception {
  final byte[] classFileMagicNumber =
    new byte[] {(byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE};
  final String xmlFileContent = "<?xml version=\"1.0\" encoding=\"UTF-8\">\n" +
    "<element>text</element>";
  final String xmlMagicNumber = "<?xml version=\"1.0\"";
  final File classFileA = new File(getTestDirectory(), "A.class");
  final File xmlFileB = new File(getTestDirectory(), "B.xml");
  final File dir = new File(getTestDirectory(), "D");
  dir.mkdirs();
  final OutputStream classFileAStream = FileUtils.openOutputStream(classFileA);
  IOUtils.write(classFileMagicNumber, classFileAStream);
  TestUtils.generateTestData(classFileAStream, 32);
  classFileAStream.close();
  FileUtils.write(xmlFileB, xmlFileContent, StandardCharsets.UTF_8);
  IOFileFilter filter = new MagicNumberFileFilter(xmlMagicNumber);
  assertFiltering(filter, classFileA, false);
  assertFiltering(filter, xmlFileB, true);
  assertFiltering(filter, dir, false);
  filter = FileFilterUtils.magicNumberFileFilter(xmlMagicNumber);
  assertFiltering(filter, classFileA, false);
  assertFiltering(filter, xmlFileB, true);
  assertFiltering(filter, dir, false);
}

代码示例来源:origin: commons-io/commons-io

@Test
public void testMagicNumberFileFilterBytes() throws Exception {
  final byte[] classFileMagicNumber =
    new byte[] {(byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE};
  final String xmlFileContent = "<?xml version=\"1.0\" encoding=\"UTF-8\">\n" +
    "<element>text</element>";
  final File classFileA = new File(getTestDirectory(), "A.class");
  final File xmlFileB = new File(getTestDirectory(), "B.xml");
  final File emptyFile = new File(getTestDirectory(), "C.xml");
  final File dir = new File(getTestDirectory(), "D");
  dir.mkdirs();
  final OutputStream classFileAStream = FileUtils.openOutputStream(classFileA);
  IOUtils.write(classFileMagicNumber, classFileAStream);
  TestUtils.generateTestData(classFileAStream, 32);
  classFileAStream.close();
  FileUtils.write(xmlFileB, xmlFileContent, StandardCharsets.UTF_8);
  FileUtils.touch(emptyFile);
  IOFileFilter filter = new MagicNumberFileFilter(classFileMagicNumber);
  assertFiltering(filter, classFileA, true);
  assertFiltering(filter, xmlFileB, false);
  assertFiltering(filter, emptyFile, false);
  assertFiltering(filter, dir, false);
  filter = FileFilterUtils.magicNumberFileFilter(classFileMagicNumber);
  assertFiltering(filter, classFileA, true);
  assertFiltering(filter, xmlFileB, false);
  assertFiltering(filter, emptyFile, false);
  assertFiltering(filter, dir, false);
}

相关文章

FileUtils类方法