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

例如,如何读取 20 行readFile或 n 行并将其保存到另一个文件(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);

}

}


动漫人物
浏览 99回答 3
3回答

梵蒂冈之花

假设您的代码工作正常:public static List<String> readFile(int n) throws IOException {&nbsp; &nbsp; try(BufferedReader br = new BufferedReader(new&nbsp;FileReader("C:\\\\\\\\Users\\\\\\\\Admin\\\\\\\\Desktop\\\\\\\\Work Files\\\\\\\\314-&nbsp;WO0000001133814\\\\\\\\Cards\\\\\\\\MBD10760_182.out"))){&nbsp; &nbsp; &nbsp; &nbsp; List<String> listOfData = new ArrayList<>();&nbsp; &nbsp; &nbsp; &nbsp; String d;&nbsp; &nbsp; &nbsp; &nbsp; while((d = br.readLine()) != null && n>0){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; listOfData.add(d);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; n--;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return listOfData;&nbsp; &nbsp; }只是你必须告诉循环它应该读多少行。如果文件少于 n 行,则 while 循环的第一条语句将返回 null 并中断循环。否则,当它读取 n 行时,由于 while 循环中的第二条语句,它将再次中断循环

长风秋雁

只需在检查 listOfData 大小时添加:&nbsp;while( ((d = br.readLine()) != null) && listOfData.size()<20 ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; listOfData.add(d);}

叮当猫咪

&nbsp;public static void main(String[] args) throws IOException {&nbsp; &nbsp; &nbsp;Path pathFrom = Paths.get("C:\\Users\\Admin\\Desktop\\Work Files\\314-WO0000001133814\\Cards\\MBD10760_182.out\"");&nbsp; &nbsp; &nbsp;Path pathTo = Paths.get("C:\\Users\\Admin\\Desktop\\Work Files\\314-WO0000001133814\\Cards\\MBD10760_187.out\"");&nbsp; &nbsp; &nbsp;Files.write(pathTo, Files.lines(pathFrom).limit(20).collect(Collectors.toList()));&nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java