filewriter只显示最后一行

scyqe7ek  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(443)

当我使用 System.out.println(data) ,它显示“filename.txt”的内容(所有行)。但是,当我使用 myWriter.write(data) ,它只写入初始文件的最后一行。我的任务是读取一个文件(在本例中, filename.txt )并将其内容复制到新文件中( new.txt ).

package javaapplication13;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.FileWriter;
import java.io.IOException;

public class readFile {
    public static String data;

    public static void main(String[] args) throws IOException{
        try{
            File myObj = new File("C:\\Users\\Admin\\Documents\\NetBeansProjects\\JavaApplication13\\src\\javaapplication13\\filename.txt");
            try (Scanner myReader = new Scanner(myObj)) { 
                do{ 
                     data = myReader.nextLine();   
                }
                while (myReader.hasNextLine());

                  PrintWriter out = new PrintWriter("C:\\Users\\Admin\\Documents\\NetBeansProjects\\JavaApplication13\\src\\javaapplication13\\new.txt");
                  FileWriter myWriter = new FileWriter("C:\\Users\\Admin\\Documents\\NetBeansProjects\\JavaApplication13\\src\\javaapplication13\\new.txt");
                  myWriter.write(data);

                  myWriter.close();
                  out.close();
                  myReader.close();

            } 
        } 
        catch (FileNotFoundException e){
            System.out.println("An error occurred.");
        }
    }
}
wpx232ag

wpx232ag1#

循环的每一次迭代都会打开一个新的writer,然后写入它,从而覆盖文件。相反,您应该在循环之前打开writer一次,然后在完成编写之后关闭它。例如。:

try (FileWriter myWriter = new FileWriter("C:\\Users\\Admin\\Documents\\NetBeansProjects\\JavaApplication13\\src\\javaapplication13\\new.txt")) {
    while (myReader.hasNextLine());
        myWriter.write(myReader.nextLine());
    } 
}

相关问题