Javareplace文本文件中的行

如何replace文本文件中find的一行文本?

我有一个string,如:

Do the dishes0 

我想要更新它:

 Do the dishes1 

(反之亦然)

我如何做到这一点?

 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) { } 

顺便说一下,我只想replace读取的行。 不是整个文件。

testing和工作

 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")); String line; StringBuffer inputBuffer = new StringBuffer(); while ((line = file.readLine()) != null) { inputBuffer.append(line); inputBuffer.append('\n'); } String inputStr = inputBuffer.toString(); file.close(); System.out.println(inputStr); // check that it's inputted right // this if structure determines whether or not to replace "0" or "1" if (Integer.parseInt(type) == 0) { inputStr = inputStr.replace(replaceWith + "1", replaceWith + "0"); } else if (Integer.parseInt(type) == 1) { inputStr = inputStr.replace(replaceWith + "0", replaceWith + "1"); } // check if the new input is right 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."); } } public static void main(String[] args) { replaceSelected("Do the dishes", "1"); } 

原始文本文件内容:

做菜
喂狗0
清理我的房间

输出:

做菜
喂狗0
清理我的房间
———————————-
做菜1
喂狗0
清理我的房间

新的文本文件内容:

做菜1
喂狗0
清理我的房间


而且,如果文本文件是:

做菜1
喂狗0
清理我的房间

你用的方法replaceSelected("Do the dishes", "1"); ,它只是不会改变文件。

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

基本上你把整个文件读到一个List ,编辑列表,最后把列表写回文件。

FILE_PATH表示文件的Path

那么你需要使用JFileChooser获取文件,然后使用扫描器和hasNext()函数读取文件的行

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

一旦你这样做,你可以将行保存到一个variables,并操纵内容。

如果更换长度不同:

  1. 阅读文件,直到find想要replace的string。
  2. 把你想要replace的文本之后的部分读入内存,全部。
  3. 在要replace的部分开始处截断文件。
  4. 写replace。
  5. 写第2步的文件的其余部分。

如果更换长度相同:

  1. 阅读文件,直到find想要replace的string。
  2. 将文件位置设置为要replace的部分的起始位置。
  3. 写replace,覆盖文件的一部分。

这是最好的,你可以得到,与您的问题的限制。 但是,至less有问题的例子是replace相同长度的string,所以第二种方法应该工作。

另请注意:Javastring是Unicode文本,而文本文件是带有一些编码的字节。 如果编码是UTF8,并且您的文本不是Latin1(或普通的7位ASCII),则必须检查编码的字节数组的长度,而不是Javastring的长度。

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

请记住,您必须重新编写文本文件。 首先我读整个文件,并将其存储在一个string中。 然后,我将每行存储为一个string数组的索引,例如:line 1 = array index 0.然后编辑对应于您想要编辑的行的索引。 一旦完成,我将数组中的所有string连接成一个string。 然后,我将新的string写入文件,该文件覆盖旧的内容。 不要担心丢失旧内容,因为它已经被编辑了。 下面是我使用的代码。

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

和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; } } 

只是如何replacestring:)因为我做的第一个参数将文件名第二个目标string第三个string被replace而不是目标

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