从文件中读取N行并将其保存到新文件

时间:2019-01-24 10:40:44

标签: java file file-io text-files

例如,如何从readFile或n行中读取20行并将其保存到另一个文件(writeFile)中?

public class Test_read_file {
  public static List<String> readFile() throws IOException {
    try(BufferedReader br = new BufferedReader(new FileReader("C:\\\\\\\\Users\\\\\\\\Admin\\\\\\\\Desktop\\\\\\\\Work Files\\\\\\\\314-WO0000001133814\\\\\\\\Cards\\\\\\\\MBD10760_182.out"))){
        List<String> listOfData = new ArrayList<>();
        String d;
        while((d = br.readLine()) != null){
            listOfData.add(d);
        }
        return listOfData;
    }
}

public static void writeFile(List<String> listOfData) throws IOException{
    try(BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\\\\\\\Users\\\\\\\\Admin\\\\\\\\Desktop\\\\\\\\Work Files\\\\\\\\314-WO0000001133814\\\\\\\\Cards\\\\\\\\MBD10760_187.out"))){
        for(String str: listOfData){
            bw.write(str);
            bw.newLine();
        }
    }
}

public static void main(String[] args) throws IOException {
    List<String> data = readFile();
    writeFile(data);
}
}

3 个答案:

答案 0 :(得分:2)

在您的代码假设有效的情况下:

public static List<String> readFile(int n) throws IOException {
    try(BufferedReader br = new BufferedReader(new 
FileReader("C:\\\\\\\\Users\\\\\\\\Admin\\\\\\\\Desktop\\\\\\\\Work Files\\\\\\\\314- 
WO0000001133814\\\\\\\\Cards\\\\\\\\MBD10760_182.out"))){
        List<String> listOfData = new ArrayList<>();
        String d;
        while((d = br.readLine()) != null && n>0){
            listOfData.add(d);
            n--;
        }
        return listOfData;
    }

只需要告诉循环它应该读多少行。如果文件少于n行,则while循环的第一条语句将返回null并将中断循环。否则,当它读取n行时,由于while循环中的第二条语句,它将再次中断循环。

答案 1 :(得分:1)

只需在检查listOfData大小时添加到:

 while( ((d = br.readLine()) != null) && listOfData.size()<20 ) {
            listOfData.add(d);
}

答案 2 :(得分:0)

 public static void main(String[] args) throws IOException {
     Path pathFrom = Paths.get("C:\\Users\\Admin\\Desktop\\Work Files\\314-WO0000001133814\\Cards\\MBD10760_182.out\"");
     Path pathTo = Paths.get("C:\\Users\\Admin\\Desktop\\Work Files\\314-WO0000001133814\\Cards\\MBD10760_187.out\"");
     Files.write(pathTo, Files.lines(pathFrom).limit(20).collect(Collectors.toList()));
 }