[英]How to copy a text file, and print out the original and copied file in Java
我正在做一個程序,需要獲取一個文本文件(test.txt)並對其進行復制並打印出來。 到目前為止,我只能打印出原始文件。 我已經在尋找一種方法來執行此操作,但似乎沒有任何我可以理解的幫助,我對Java還是很陌生。 我至少在尋找指導,而不僅僅是完整的答案。
到目前為止我的代碼...
import java.io.*;
public class Copy{
public static void main(String [] args){
try{
FileInputStream fis = new FileInputStream("test.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
File a = new File("test.txt");
FileReader fr = new FileReader(a);
File b = new File("Copied.txt");
FileWriter fw = new FileWriter(b);
while(true){
String line = br.readLine();
if(line != null){
System.out.println(line);
} else{
br.close();
break;
}
}
} catch(FileNotFoundException e){
System.out.println("Error: " + e.getMessage());
} catch(IOException e){
System.out.println("Error: " + e.getMessage());
}
}
}
再次感謝您的幫助,因為我正在嘗試學習這一點。 謝謝
通常情況下,我建議使用Files.copy
只是它的simplicty,但因為你需要“打印”在同一時間的內容,我們可以利用你的代碼。
但是,首先,作為一般經驗法則,如果將其打開,則應將其關閉。 這樣可以確保您不會打開可能影響代碼其他部分的資源。
有關更多詳細信息,請參見try-with-resources語句 。
接下來,一旦您從源文件中讀取了一行文本,則實際上需要將其寫入目標文件中,例如...
try (BufferedReader br = new BufferedReader(new FileReader("test.txt"))) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter("Copied.txt"))) {
String text = null;
while ((text = br.readLine()) != null) {
System.out.println(text);
bw.write(text);
bw.newLine();
}
}
} catch (FileNotFoundException e) {
System.out.println("Error: " + e.getMessage());
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
如果您使用的是Java 1.7或更高版本,則可以使用Files.copy()
File src = "your File"; File dest = "your copy target" Files.copy(src.toPath(),dest.toPath());
將您的FileWriter更改為PrintStream:
PrintStream fw = new PrintStream(b);
然后,您應該可以使用以下命令寫入該文件:
fw.println(line);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.