第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

從文件中讀取 N 行并將其保存到新文件中

從文件中讀取 N 行并將其保存到新文件中

動(dòng)漫人物 2022-05-21 20:55:02
例如,如何讀取 20 行readFile或 n 行并將其保存到另一個(gè)文件(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 回答

?
梵蒂岡之花

TA貢獻(xiàn)1900條經(jīng)驗(yàn) 獲得超5個(gè)贊

假設(shè)您的代碼工作正常:


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;

    }

只是你必須告訴循環(huán)它應(yīng)該讀多少行。如果文件少于 n 行,則 while 循環(huán)的第一條語(yǔ)句將返回 null 并中斷循環(huán)。否則,當(dāng)它讀取 n 行時(shí),由于 while 循環(huán)中的第二條語(yǔ)句,它將再次中斷循環(huán)


查看完整回答
反對(duì) 回復(fù) 2022-05-21
?
長(zhǎng)風(fēng)秋雁

TA貢獻(xiàn)1757條經(jīng)驗(yàn) 獲得超7個(gè)贊

只需在檢查 listOfData 大小時(shí)添加:


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

            listOfData.add(d);

}


查看完整回答
反對(duì) 回復(fù) 2022-05-21
?
叮當(dāng)貓咪

TA貢獻(xiàn)1776條經(jīng)驗(yàn) 獲得超12個(gè)贊

 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()));

 }


查看完整回答
反對(duì) 回復(fù) 2022-05-21
  • 3 回答
  • 0 關(guān)注
  • 126 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)