あるファイルを別のファイルにコピーする Java IO
質問
2 つの Java.io.File オブジェクト file1 と file2 があります。file1 の内容を file2 にコピーしたいと考えています。file1を読み取り、file2に書き込むメソッドを作成せずにこれを行う標準的な方法はありますか?
解決
いいえ、組み込みのそれをする方法何もありません。あなたが達成したいものに近いがそうのように、transferFrom
からFileOutputStream
方法です。
FileChannel src = new FileInputStream(file1).getChannel();
FileChannel dest = new FileOutputStream(file2).getChannel();
dest.transferFrom(src, 0, src.size());
そしてfinally
ブロックで例外と密接なすべてを処理することを忘れないでください。
他のヒント
あなたが怠惰なことと最小限のコードの使用を書いて離れて取得したい場合は、
FileUtils.copyFile(src, dest)
ApacheのIOCommons から
はありません。すべての長時間Javaプログラマは、このようなAの方法を含む、独自のユーティリティベルトを持っています。ここでは私のもの。
public static void copyFileToFile(final File src, final File dest) throws IOException
{
copyInputStreamToFile(new FileInputStream(src), dest);
dest.setLastModified(src.lastModified());
}
public static void copyInputStreamToFile(final InputStream in, final File dest)
throws IOException
{
copyInputStreamToOutputStream(in, new FileOutputStream(dest));
}
public static void copyInputStreamToOutputStream(final InputStream in,
final OutputStream out) throws IOException
{
try
{
try
{
final byte[] buffer = new byte[1024];
int n;
while ((n = in.read(buffer)) != -1)
out.write(buffer, 0, n);
}
finally
{
out.close();
}
}
finally
{
in.close();
}
}
以来ののJava 7 を使用することができます<のhref = "https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html" のrel = "noreferrer"> Files.copy()
のJavaの標準ライブラリから。
あなたは、ラッパー・メソッドを作成することができます
public static void copy(String sourcePath, String destinationPath) throws IOException {
Files.copy(Paths.get(sourcePath), new FileOutputStream(destinationPath));
}
以下のように使用することができます
copy("source.txt", "dest.txt");
で Java 7 使用できます Files.copy()
そして非常に重要なことは次のとおりです。 新しいファイルを作成した後は、OutputStream を閉じることを忘れないでください。.
OutputStream os = new FileOutputStream(targetFile);
Files.copy(Paths.get(sourceFile), os);
os.close();
所属していません StackOverflow