Java 替换文本文件中的行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20039980/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 22:34:54  来源:igfitidea点击:

Java Replace Line In Text File

javareplacelinejcheckbox

提问by Eveno

How do I replace a line of text found within a text file?

如何替换文本文件中的一行文本?

I have a string such as:

我有一个字符串,例如:

Do the dishes0

And I want to update it with:

我想用以下内容更新它:

Do the dishes1

(and vise versa)

(反之亦然)

How do I accomplish this?

我该如何实现?

ActionListener al = new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    JCheckBox checkbox = (JCheckBox) e.getSource();
                    if (checkbox.isSelected()) {
                        System.out.println("Selected");
                        String s = checkbox.getText();
                        replaceSelected(s, "1");
                    } else {
                        System.out.println("Deselected");
                        String s = checkbox.getText();
                        replaceSelected(s, "0");
                    }
                }
            };

public static void replaceSelected(String replaceWith, String type) {

}

By the way, I want to replace ONLY the line that was read. NOT the entire file.

顺便说一句,我只想替换已读取的行。不是整个文件。

采纳答案by Michael Yaworski

At the bottom, I have a general solution to replace lines in a file. But first, here is the answer to the specific question at hand. Helper function:

在底部,我有一个通用的解决方案来替换文件中的行。但首先,这是手头特定问题的答案。辅助功能:

public static void replaceSelected(String replaceWith, String type) {
    try {
        // input the file content to the StringBuffer "input"
        BufferedReader file = new BufferedReader(new FileReader("notes.txt"));
        StringBuffer inputBuffer = new StringBuffer();
        String line;

        while ((line = file.readLine()) != null) {
            inputBuffer.append(line);
            inputBuffer.append('\n');
        }
        file.close();
        String inputStr = inputBuffer.toString();

        System.out.println(inputStr); // display the original file for debugging

        // logic to replace lines in the string (could use regex here to be generic)
        if (type.equals("0")) {
            inputStr = inputStr.replace(replaceWith + "1", replaceWith + "0"); 
        } else if (type.equals("1")) {
            inputStr = inputStr.replace(replaceWith + "0", replaceWith + "1");
        }

        // display the new file for debugging
        System.out.println("----------------------------------\n" + inputStr);

        // write the new string with the replaced line OVER the same file
        FileOutputStream fileOut = new FileOutputStream("notes.txt");
        fileOut.write(inputStr.getBytes());
        fileOut.close();

    } catch (Exception e) {
        System.out.println("Problem reading file.");
    }
}

Then call it:

然后调用它:

public static void main(String[] args) {
    replaceSelected("Do the dishes", "1");   
}


Original Text File Content:

原始文本文件内容:

Do the dishes0
Feed the dog0
Cleaned my room1

洗碗 0
喂狗 0
打扫我的房间 1

Output:

输出:

Do the dishes0
Feed the dog0
Cleaned my room1
----------------------------------
Do the dishes1
Feed the dog0
Cleaned my room1

做盘子0
喂狗0
打扫我的房间1
----------------------------------
做盘子1
喂狗0
打扫我的房间1

New text file content:

新的文本文件内容:

Do the dishes1
Feed the dog0
Cleaned my room1

洗碗1
喂狗0
打扫我的房间1



And as a note, if the text file was:

请注意,如果文本文件是:

Do the dishes1
Feed the dog0
Cleaned my room1

洗碗1
喂狗0
打扫我的房间1

and you used the method replaceSelected("Do the dishes", "1");, it would just not change the file.

并且您使用了该方法replaceSelected("Do the dishes", "1");,它不会更改文件。



Since this question is pretty specific, I'll add a more general solution here for future readers (based on the title).

由于这个问题非常具体,我将在这里为未来的读者添加一个更通用的解决方案(基于标题)。

// read file one line at a time
// replace line as you read the file and store updated lines in StringBuffer
// overwrite the file with the new lines
public static void replaceLines() {
    try {
        // input the (modified) file content to the StringBuffer "input"
        BufferedReader file = new BufferedReader(new FileReader("notes.txt"));
        StringBuffer inputBuffer = new StringBuffer();
        String line;

        while ((line = file.readLine()) != null) {
            line = ... // replace the line here
            inputBuffer.append(line);
            inputBuffer.append('\n');
        }
        file.close();

        // write the new string with the replaced line OVER the same file
        FileOutputStream fileOut = new FileOutputStream("notes.txt");
        fileOut.write(inputBuffer.toString().getBytes());
        fileOut.close();

    } catch (Exception e) {
        System.out.println("Problem reading file.");
    }
}

回答by Corjava

Well you would need to get a file with JFileChooser and then read through the lines of the file using a scanner and the hasNext() function

好吧,您需要使用 JFileChooser 获取文件,然后使用扫描仪和 hasNext() 函数读取文件的行

http://docs.oracle.com/javase/7/docs/api/javax/swing/JFileChooser.html

http://docs.oracle.com/javase/7/docs/api/javax/swing/JFileChooser.html

once you do that you can save the line into a variable and manipulate the contents.

完成后,您可以将行保存到变量中并操作内容。

回答by hyde

If replacement is of different length:

如果替换长度不同:

  1. Read file until you find the string you want to replace.
  2. Read into memory the part aftertext you want to replace, all of it.
  3. Truncate the file at start of the part you want to replace.
  4. Write replacement.
  5. Write rest of the file from step 2.
  1. 读取文件,直到找到要替换的字符串。
  2. 将要替换的文本后面的部分全部读入内存。
  3. 在要替换的部分的开头截断文件。
  4. 写替换。
  5. 写入第 2 步中的文件的其余部分。

If replacement is of same length:

如果替换长度相同:

  1. Read file until you find the string you want to replace.
  2. Set file position to start of the part you want to replace.
  3. Write replacement, overwriting part of file.
  1. 读取文件,直到找到要替换的字符串。
  2. 将文件位置设置为要替换的部分的开头。
  3. 写替换,覆盖文件的一部分。

This is the best you can get, with constraints of your question. However, at least the example in question is replacing string of same length, So the second way should work.

这是你能得到的最好的,但你的问题有限制。但是,至少有问题的例子是替换相同长度的字符串,所以第二种方法应该有效。

Also be aware: Java strings are Unicode text, while text files are bytes with some encoding. If encoding is UTF8, and your text is not Latin1 (or plain 7-bit ASCII), you have to check length of encoded byte array, not length of Java string.

还要注意:Java 字符串是 Unicode 文本,而文本文件是带有某种编码的字节。如果编码是 UTF8,并且您的文本不是 Latin1(或纯 7 位 ASCII),您必须检查编码字节数组的长度,而不是 Java 字符串的长度。

回答by Tuupertunut

Since Java 7 this is very easy and intuitive to do.

从 Java 7 开始,这非常容易且直观。

List<String> fileContent = new ArrayList<>(Files.readAllLines(FILE_PATH, StandardCharsets.UTF_8));

for (int i = 0; i < fileContent.size(); i++) {
    if (fileContent.get(i).equals("old line")) {
        fileContent.set(i, "new line");
        break;
    }
}

Files.write(FILE_PATH, fileContent, StandardCharsets.UTF_8);

Basically you read the whole file to a List, edit the list and finally write the list back to file.

基本上,您将整个文件读到 a List,编辑列表,最后将列表写回文件。

FILE_PATHrepresents the Pathof the file.

FILE_PATH代表Path文件的。

回答by holycatcrusher

I was going to answer this question. Then I saw it get marked as a duplicate of this question, after I'd written the code, so I am going to post my solution here.

我是来回答这个问题的。然后我看到它被标记为这个问题的重复,在我写了代码之后,所以我要在这里发布我的解决方案。

Keeping in mind that you have to re-write the text file. First I read the entire file, and store it in a string. Then I store each line as a index of a string array, ex line one = array index 0. I then edit the index corresponding to the line that you wish to edit. Once this is done I concatenate all the strings in the array into a single string. Then I write the new string into the file, which writes over the old content. Don't worry about losing your old content as it has been written again with the edit. below is the code I used.

请记住,您必须重新编写文本文件。首先我读取整个文件,并将其存储在一个字符串中。然后我将每一行存储为一个字符串数组的索引,ex line one = array index 0。然后我编辑与您希望编辑的行相对应的索引。完成后,我将数组中的所有字符串连接成一个字符串。然后我将新字符串写入文件,该文件覆盖旧内容。不要担心丢失旧内容,因为它已通过编辑再次写入。下面是我使用的代码。

public class App {

public static void main(String[] args) {

    String file = "file.txt";
    String newLineContent = "Hello my name is bob";
    int lineToBeEdited = 3;

    ChangeLineInFile changeFile = new ChangeLineInFile();
    changeFile.changeALineInATextFile(file, newLineContent, lineToBeEdited);



}

}

And the class.

和班级。

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;

public class ChangeLineInFile {

public void changeALineInATextFile(String fileName, String newLine, int lineNumber) {
        String content = new String();
        String editedContent = new String();
        content = readFile(fileName);
        editedContent = editLineInContent(content, newLine, lineNumber);
        writeToFile(fileName, editedContent);

    }

private static int numberOfLinesInFile(String content) {
    int numberOfLines = 0;
    int index = 0;
    int lastIndex = 0;

    lastIndex = content.length() - 1;

    while (true) {

        if (content.charAt(index) == '\n') {
            numberOfLines++;

        }

        if (index == lastIndex) {
            numberOfLines = numberOfLines + 1;
            break;
        }
        index++;

    }

    return numberOfLines;
}

private static String[] turnFileIntoArrayOfStrings(String content, int lines) {
    String[] array = new String[lines];
    int index = 0;
    int tempInt = 0;
    int startIndext = 0;
    int lastIndex = content.length() - 1;

    while (true) {

        if (content.charAt(index) == '\n') {
            tempInt++;

            String temp2 = new String();
            for (int i = 0; i < index - startIndext; i++) {
                temp2 += content.charAt(startIndext + i);
            }
            startIndext = index;
            array[tempInt - 1] = temp2;

        }

        if (index == lastIndex) {

            tempInt++;

            String temp2 = new String();
            for (int i = 0; i < index - startIndext + 1; i++) {
                temp2 += content.charAt(startIndext + i);
            }
            array[tempInt - 1] = temp2;

            break;
        }
        index++;

    }

    return array;
}

private static String editLineInContent(String content, String newLine, int line) {

    int lineNumber = 0;
    lineNumber = numberOfLinesInFile(content);

    String[] lines = new String[lineNumber];
    lines = turnFileIntoArrayOfStrings(content, lineNumber);

    if (line != 1) {
        lines[line - 1] = "\n" + newLine;
    } else {
        lines[line - 1] = newLine;
    }
    content = new String();

    for (int i = 0; i < lineNumber; i++) {
        content += lines[i];
    }

    return content;
}

private static void writeToFile(String file, String content) {

    try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"))) {
        writer.write(content);
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

private static String readFile(String filename) {
    String content = null;
    File file = new File(filename);
    FileReader reader = null;
    try {
        reader = new FileReader(file);
        char[] chars = new char[(int) file.length()];
        reader.read(chars);
        content = new String(chars);
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    return content;
}

}

回答by amar

just how to replace strings :) as i do first arg will be filename second target string third one the string to be replaced instead of targe

只是如何替换字符串 :) 就像我做的第一个 arg 将是文件名 第二个目标字符串 第三个要替换的字符串而不是 targe

public class ReplaceString{
      public static void main(String[] args)throws Exception {
        if(args.length<3)System.exit(0);
        String targetStr = args[1];
        String altStr = args[2];
        java.io.File file = new java.io.File(args[0]);
        java.util.Scanner scanner = new java.util.Scanner(file);
        StringBuilder buffer = new StringBuilder();
        while(scanner.hasNext()){
          buffer.append(scanner.nextLine().replaceAll(targetStr, altStr));
          if(scanner.hasNext())buffer.append("\n");
        }
        scanner.close();
        java.io.PrintWriter printer = new java.io.PrintWriter(file);
        printer.print(buffer);
        printer.close();
      }
    }