【问题标题】:How to edit an original text file and break the lines that reaches a maximum length. Java如何编辑原始文本文件并打破达到最大长度的行。爪哇
【发布时间】:2015-06-29 04:14:21
【问题描述】:

我有一个文本文件,我想通过设置每行要中断的最大长度来组织它,然后再创建一个新行。我知道我可以打开、读取和写入文件,但我可以修复同一个文件而无需创建新文件吗?

我尝试编写不同的代码来做到这一点,但我仍然对 IO API 有一点经验,而且我总是遇到问题。这是我到目前为止没有任何问题的想法:

public static void main(String[] args) {
        File file = new File("data/test.txt");
        BufferedReader br = null;
        BufferedWriter bw = null;

        try {
            br = new BufferedReader(new FileReader(file));
            bw = new BufferedWriter(new FileWriter(file));
            final int MAX_LENGTH = 80;
            String line;

            while((line = br.readLine()) != null) {
                if(line.length() > MAX_LENGTH) {
                    //I want to break the line if it reached the MAX_LENGTH
                    //without overwriting data or skipping them
                }
            }
            br.close();
            bw.close();
        } catch(IOException e) {
            e.printStackTrace();
        }
    }

我也将不胜感激有关我的代码的任何建议或想法。

【问题讨论】:

  • 将新内容写入临时文件,完成后,删除原始文件并将临时文件重命名到它的位置
  • @MadProgrammer 我知道,但是否可以在同一个文件上写入而无需创建新文件?
  • 不,不是。如果您愿意,您必须不断向前阅读,将文件的内容“向下”移动到您想要进行的更改范围之外......更容易使用临时文件
  • @MadProgrammer 确实如此,但是当我使用临时文件时,我会做几乎相同的事情。在这句话的那一行变得合法之前,我仍然需要向前阅读,你不觉得吗?
  • 不是真的,您从原始文件中读取该行,将您想要的行数添加到新文件并重复。会更快

标签: java file buffer


【解决方案1】:

写入文件是破坏性的过程,即使以可搜索模式打开文件,写入文件的某个位置也会简单地覆盖那里的内容。就个人而言,我会使用第二个文件将更改写入,然后删除原始文件并将临时文件重命名回原处

File original = new File("data/test.txt");
File tmp = new File("data/temp.txt");

try {
    try (BufferedReader br = new BufferedReader(new FileReader(original))) {
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(tmp))) {

            String text = null;
            while ((text = br.readLine()) != null) {

                // For each line we read, we need to break the line
                // down to the MAX_LENGTH and write
                StringBuilder sb = new StringBuilder(text);
                while (sb.length() > MAX_LENGTH) {
                    String line = sb.substring(0, MAX_LENGTH);
                    sb.delete(0, MAX_LENGTH);
                    bw.write(line);
                    bw.newLine();
                }
                // In case we removed all the text during the previous loop
                if (sb.length() > 0) {
                    bw.write(sb.toString());
                    bw.newLine();
                }

            }

        }
    }

    if (original.delete()) {
        tmp.renameTo(original);
    } else {
        throw new IOException("Failed to remove " + original);
    }
} catch (IOException exp) {
    exp.printStackTrace();
}

作为一个想法

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多