Java Replace Line in Text File

Java Replace Line In Text File

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

Output:

Do the dishes0

Feed the dog0

Cleaned my room1

----------------------------------

Do the dishes1

Feed the dog0

Cleaned my room1

New text file content:

Do the dishes1

Feed the dog0

Cleaned my room1


And as a note, if the text file was:

Do the dishes1

Feed the dog0

Cleaned my room1

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


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

How to replace specific String in a text file by java?

In general you can do it in 3 steps:

  1. Read file and store it in String
  2. Change the String as you need (your "username,password..." modification)
  3. Write the String to a file

You can search for instruction of every step at Stackoverflow.

Here is a possible solution working directly on the Stream:

public static void main(String[] args) throws IOException {

String inputFile = "C:\\Users\\geheim\\Desktop\\lines.txt";
String outputFile = "C:\\Users\\geheim\\Desktop\\lines_new.txt";

try (Stream<String> stream = Files.lines(Paths.get(inputFile));
FileOutputStream fop = new FileOutputStream(new File(outputFile))) {
stream.map(line -> line += " manipulate line as required\n").forEach(line -> {
try {
fop.write(line.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
});
}
}

How to replace specific line in text file.java

Create and open a stream to the file. Then, in a loop read line by line and write to a new file which you created using another stream, when your loop counter variable equals the line number you want, then write the new line instead of that one, let the loop finish. Finally, close both streams. Remember that the first line is not 1 but rather 0. Remember that you must loop until reaching the end of file, you must maintain a loop variable independently, this means you can't use a for loop, but rather a while loop.

Java replace line in a text file

Use System.lineSeparator() instead of \n.

while ((line = file.readLine()) != null)
input += line + System.lineSeparator();

The issue is that on Unix systems, the line separator is \n while on Windows systems, it's \r\n.

In Java versions older then Java 7, you would have to use System.getProperty("line.separator") instead.

As pointed out in the comments, if you have concerns about memory usage, it would be wise to not store the entire output in a variable, but write it out line-by-line in the loop that you're using to process the input.

How to replace a line in a text file using Java?

This can be done in-place on a single file only if you are sure that the string you are replacing is exactly the same length in bytes as the string that replaces it. Otherwise, you can't add or delete characters in a single file, but you can create a new file.

  1. Open the source file for reading.
  2. Open the destination file for writing.
  3. Read each line in the source file, use replaceAll, and write it to the destination file.
  4. Close both files.

Alternate method that preserves the key-value semantics:

  1. Open the source file for reading.
  2. Open the destination file for writing.
  3. Split each line in the source file into a key and value pair. If the key equals "content_style", write the key and "dirty" to the destination file. Otherwise write the key and value.
  4. Close both files.

Finally, delete the old file and rename the new file on top of the old one. If you're going to be doing key-value manipulations often, and you don't want to write out a new file all the time, it might be worth it to use a database. Look for a JDBC driver for SQLite.

How to replace a specific line in a file using Java?

If you are using Java 7 or higher and if lineNumber starts in 1, you can do the following:

public static void setVariable(int lineNumber, String data) throws IOException {
Path path = Paths.get("data.txt");
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
lines.set(lineNumber - 1, data);
Files.write(path, lines, StandardCharsets.UTF_8);
}

Obviously if lineNumber starts in 0, then:

lines.set(lineNumber, data);


Related Topics



Leave a reply



Submit