簡體   English   中英

寫入Java中的指定行?

[英]Writing to specified line in Java?

為了澄清我的問題,我正在寫一個位於我的計算機上的文本文件,其中已經包含文本內容。 下面的代碼寫入文本文件而不刪除其任何內容,但現在我想指定它寫入的行。 目前,它有一個 if 語句來捕獲該行中是否存在“完成”一詞,因為它確實寫入文件,所以它被識別。 我的問題是試圖讓它寫入寫着“完成”的行。 它寫入最底部的最后一行代碼。 我怎樣才能解決這個問題?

方法 readNumLines 是文件中包含的行數。 Reading 是文本文件名。

int i = 0;
    BufferedReader reader = new BufferedReader(new FileReader(path+reading));
    BufferedWriter writer = new BufferedWriter(new FileWriter(path+reading, true));
    String line = null;
    while ((line = reader.readLine()) != null && i < readNumLines(reading)-1) {
        if(line.contains("Done")){
            writer.write("\nCHECK!\n");
            writer.close();
        }
        i++;
    }

我建議將整個文件讀入一個變量(字符串、數組或列表)。 然后,您可以輕松地修改特定行並將所有內容寫回文件。

1) 將文件讀入數組:將文本文件內容逐行存入數組

2) 操作數組:

for (int i = 0; i < lines.length; i++) {
            String line = lines[i];
            if (line.contains("Done")) {
                lines[i] = line + "\nCHECK!\n";
                break;
            }
}

3) 將字符串數組寫入文件:使用 Java 將字符串數組寫入文件 - 單獨的行

該問題也可能與此行有關:

writer.write("\nCHECK!\n");

第一個“\n”強制將“CHECK”寫入新行。 這假定您的“完成”行是最后一行並且不以“\n”結尾。

這是我的做法。想法很簡單,將包括新行在內的所有內容寫入臨時文件,然后將臨時文件重命名為原始文件並刪除原始文件。 注意:我從我的一個項目中提取了此代碼,因此我可能忘記更改某些內容。 因此,如果它不起作用,請告訴我,我會看看。 希望這可以幫助 :)

            String line;//You need to specify those
            File infile;

            // temp file
            File outFile = new File("$$$$$$$$.tmp");

            // input
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(inFile);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            BufferedReader in = new BufferedReader(new InputStreamReader(fis));

            // output         
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(outFile);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            PrintWriter out = new PrintWriter(fos);
            String thisLine = "";
            int i =1;
            try {
                while ((thisLine = in.readLine()) != null) {
                   if(in.contains("Done"))//the check for done 
                       out.println(line);                  
                   }
                   out.println(thisLine);
                   i++;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            out.flush();
            out.close();
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            inFile.delete();
            outFile.renameTo(inFile);

使用Java 8時,您可以嘗試以下操作:

final Path myFile = Paths.get("path\\to\\yourFile.txt");
final int lineNumWhereToInsert = 2;
final String stringToInsert = "insertion test";

try {
    final List<String> lines = Files.lines(myFile).collect(Collectors.toList());
    lines.add(Math.min(lineNumWhereToInsert, lines.size()), stringToInsert);

    try (final BufferedWriter out = Files.newBufferedWriter(myFile, Charset.forName("UTF-8"))) {
        for (final String line : lines) {
            out.append(line).append(System.lineSeparator());
        }
    }
} catch (IOException) {
    ex.printStrackTrace();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM