Javaは、ファイルを処理できるIO操作クラスを提供します。しかし、ファイルをコピーする方法はありません。ファイルをコピーすることは、プログラムが関連する多くのファイルを処理する必要がある場合に重要な操作です。ただし、Javaファイルをコピーするにはいくつかの方法があり、以下が最も一般的な方法です。
1. Filestreamsを使用してコピーします
これは、あるファイルの内容を別のファイルにコピーする最も古典的な方法です。 FileInputStreamを使用してファイルAのバイトを読み取り、FileOutputStreamを使用してファイルBに書き込みます。これは最初の方法のコードです。
private static void copyfileusingfileStreams(ファイルソース、ファイルdest)throws ioexception {inputstream input = null; outputStream output = null; try {input = new fileinputStream(source); output = new fileoutputStream(dest); byte [] buf = new byte [1024]; int bytesRead; while((bytesread = input.read(buf))> 0){output.write(buf、0、bytesread); }}最後に{input.close(); output.close(); }}ご覧のとおり、データを試すためにいくつかの読み取りおよび書き込み操作を実行するため、これは非効率的な方法である必要があり、次の方法で新しい方法が表示されます。
2。FileChannelを使用してコピーします
Java Nioには、Transfer -Fromメソッドが含まれており、ドキュメントに基づいてファイルストリームよりも速くコピーする必要があります。 2番目の方法のコードは次のとおりです。
private static void copyfileusingfileChannels(ファイルソース、ファイルデスティ)をスローIoException {fileChannel inputChannel = null; FileChannel OutputChannel = null; try {inputChannel = new FileInputStream(source).getChannel(); outputChannel = new fileoutputStream(dest).getChannel(); outputChannel.transferfrom(inputChannel、0、inputChannel.size()); }最後に{inputChannel.close(); outputChannel.close(); }}3.コモンズIOを使用してコピーします
Apache Commons IOは、FileUtilsクラスにコピーファイルメソッドを提供します。これは、1つのファイルを別のファイルにコピーするために使用できます。既にプロジェクトを使用しているときに、Apache Commons Fileutilsクラスを使用する場合、非常に便利です。基本的に、このクラスではJava nio Filechannel内部を使用しています。これは、3番目の方法のコードです。
private static void copyfileusingapachecommonsio(file source、file dest)throws ioexception {fileutils.copyfile(source、dest); }4. Java7のファイルクラスを使用してコピーします
Java 7で何らかの経験がある場合は、コピー方法を使用してあるファイルから別のファイルにコピーできることがわかる場合があります。これは、4番目の方法のコードです。
private static void copyfileusjava7files(ファイルソース、ファイルdest)をthrows ioexception {files.copy(source.topath()、dest.topath()); }Javaファイルを別のディレクトリにコピーするための実装コードを見てみましょう。特定のコードは次のとおりです。
パッケージcom.util; import java.io.file; import java.io.fileinputStream; import java.io.fileoutputStream; Import java.io.inputStream; public class testhtml {/** *単一ファイル *コピー * @param oldpath文字列元ファイルパス@return boolean */ public void copyfile(string oldpath、string newpath){try {int bytesum = 0; int byteread = 0;ファイルoldfile = new file(oldpath); if(oldfile.exists()){// inputstream instream = new fileinputStream(oldpath); //元のfile fileoutputStream fs = new fileoutputStream(newPath)で読み取ります。 byte [] buffer = new byte [1444]; int length; while((byteread = instream.read(buffer))!= -1){bytesum += byteread; // bytesファイルサイズsystem.out.println(bytesum); fs.write(buffer、0、byteread); } instream.close(); }} catch(Exception E){System.out.println( "単一のファイルをコピーするエラー"); e.printstacktrace();}}/** *フォルダー全体をコピーします。コンテンツ全体をコピー * @param oldpath文字列元ファイルパス:c:/fqf * @param newpath stringパスコピー後:f:/fqf/ff * @return boolean */public void copyfolder(string old、newpath){try {mkdir)。 //フォルダーが存在しない場合は、新しいフォルダーファイルa = newファイル(OldPath)を作成します。 string [] file = a.list();ファイルtemp = null; for(int i = 0; i <file.length; i ++){if(oldpath.endswith(file.separator)){temp = new file(oldpath+file [i]); } else {temp = new file(oldpath+file.separator+file [i]); } if(temp.isfile()){fileinputStream input = new fileInputStream(temp); fileoutputStream output = new fileoutputStream(newPath + "/" +(temp.getName())。toString()); byte [] b = new byte [1024 * 5]; int len; while((len = input.read(b))!= -1){output.write(b、0、len); } output.flush(); output.close(); input.close(); } if(temp.isdirectory()){//サブフォルダーCopyFolder(OldPath+"/"+file [i]、newpath+"/"+file [i]); }}} catch(Exception e){system.out.println( "フォルダーコンテンツ操作全体をコピーするエラー"); e.printstacktrace();}} public static void main(string [] args)throws exception {// //これはあなたのソースファイルです。 Afterfile = new file( "c:/users/administrator/desktop/jiekou0/untitled-2.html"); //// // // fileinputStream fis = new fileinputStream(befuidefile); /// fileoutputStream(aftherfile); /// //ファイルキャッシュ領域// byte [] b = new byte [1024]; // //ファイルキャッシュ領域のファイルストリーム情報を読み取ります。読み取り結果が-1でない場合、ファイルが読み取られておらず、読み取られていることを意味します。// OldPath = "C:/Users/administrator/desktop/untitled-2.html"; string newpath = "c:/users/administrator/desktop/jiekou0/untitled-2.html"; testhtml t = new testhtml(); t.copyfile(new path、new path、new path、new testhtml();要約します
上記は、Javaにファイルをコピーする4つの方法と、ファイルをエディターが紹介した別のディレクトリにコピーする例です。私はそれが誰にでも役立つことを願っています。ご質問がある場合は、メッセージを残してください。編集者は、すべての人に時間内に返信します。 wulin.comのウェブサイトへのご支援ありがとうございます!