java_IO_文字(txt)檔案複製
阿新 • • 發佈:2021-01-18
我這裡只是提供簡單的成品程式碼,不明白的點請看我前面寫的有關IO的基礎知識,通常使用“程式碼2”
程式碼1(節點流):
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class CopyFile {
public static void main(String[] args) {
File f1 = new File("src/foryou/IO/hello3.txt" );
File f2 = new File("src/foryou/IO/hello3_copy.txt");
FileReader read = null;
FileWriter write = null;
try {
read = new FileReader(f1);
write = new FileWriter(f2);
char c[] =new char[10];
int len;
while((len = read.read(c)) != -1) {
write.write(c, 0, len);
}
} catch (Exception e) {
System.out.println(e);
}finally {
try {
if(write!=null) {
write.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(read!=null) {
read.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
System.out. println("copy is completed");
}
}
程式碼2:(緩衝流)
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileReder_WriterCopyFile {
public static void main(String[] args) {
File f1 = new File("src/foryou/IO/hello3.txt");
File f2 = new File("src/foryou/IO/hello3_copy.txt");
BufferedReader bread = null;
BufferedWriter bwrite = null;
try {
bread = new BufferedReader(new FileReader(f1));
bwrite = new BufferedWriter(new FileWriter(f2));
char c[] =new char[10];
String data;
//以一行為單位進行讀取
while((data = bread.readLine()) != null) {
bwrite.write(data);
}
} catch (Exception e) {
System.out.println(e);
}finally {
try {
if(bwrite!=null) {
bwrite.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(bread!=null) {
bread.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("copy is completed");
}
}
結果: