Rewrite a specific line in a txt file - java

I was trying to rewrite a line that contains student details in a txt file. There will be a list of students' detail in the file, for example:
Name1,10
Name2,20
Name3,30
I tried to rewrite Name2,20 to Name2,13 using a BufferedReader to find the line with Name2. And a BufferedWriter to replace the line with new text, but it turns out the code will write my whole txt file to null.
Here's my code:
String lineText;
String newLine = "Name,age";
try {
BufferedReader br = new BufferedReader(new FileReader(path));
BufferedWriter bw = new BufferedWriter(new FileWriter(path,false));
while ((lineText = br.readLine()) != null){
System.out.println(">" + lineText);
String studentData[] = lineText.split(",");
if(studentData[0].equals(Name2)){
bw.write(newLine);
}
System.out.println(lineText);
}
br.close();
bw.close();
}
catch (IOException e) {
e.printStackTrace();
}
Can anyone please tell me how to rewrite a specific line in txt file?

Easiest way is to read the entire file, and store it in a variable. Replacing the line in question while reading the current file.
Something like:
String lineText;
String newLine = "Name,age";
try {
BufferedReader br = new BufferedReader(new FileReader(path));
BufferedWriter bw = new BufferedWriter(new FileWriter(path,false));
String currentFileContents = "";
while ((lineText = br.readLine()) != null){
System.out.println(">" + lineText);
String studentData[] = lineText.split(",");
if(studentData[0].equals("Name2")){
currentFileContents += newLine;
} else {
currentFileContents += lineText;
}
}
bw.write(currentFileContents);
br.close();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}

Related

I have a filewriter method that only ouputs to the file when i close it

String filePath = "Seat";
static void modifyFile(String filePath, String oldString, String newString) {
File fileToBeModified = new File(filePath);
String oldContent = "";
BufferedReader reader = null;
BufferedWriter writer = null;
try {
reader = new BufferedReader(new FileReader(fileToBeModified));
//Reading all the lines of input text file into oldContent
String line = reader.readLine();
while (line != null) {
oldContent = oldContent + line + System.lineSeparator();
line = reader.readLine();
}
//Replacing oldString with newString in the oldContent
String newContent = oldContent.replaceAll(oldString, newString);
//Rewriting the input text file with newContent
writer = new BufferedWriter(new FileWriter(fileToBeModified));
writer.write(newContent);
writer.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
//Closing the resources
reader.close();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This method is meant to change a certain line in a file the method itself works when run but it only changes the line when i close the program which is when it closes the writer, i looked it up and add writer.flush() earlier on in the code to see if that would work but i still have the same problem
You are trying to read from and write to the same file.
You cannot do both operations at the same time as the file will get locked. close the reader and then do the write operation.

Can't write all list to the file

I have an ArrayList list of some lines from text file. I am trying to find these lines in a text file, if I find it I want to write it to another text file and delete it from the original file.
I wrote a code for that, it is working but not for the whole list, sometimes take one line and sometimes take more. and give me this message:
1 R101 100850 0
Exception caught : java.io.IOException: Stream closed
static void moveLines(ArrayList posList, int topic) {
//=======================To read lines=======
File inputFile = new File("U:\\Research\\Projects\\sef\\enhancfeaturtm\\TestData\\topic\\" + "Test" + topic + ".txt");
File outputFile = new File("U:\\Research\\Projects\\sef\\enhancfeaturtm\\TestData\\topic\\" + "Training" + topic + ".txt");
try {
FileReader fr = new FileReader(inputFile);
BufferedReader br = new BufferedReader(fr);
FileWriter fr1 = new FileWriter(outputFile);
BufferedWriter writer = new BufferedWriter(fr1);
String line;
int count = 1;
int z = 1;
while ((line = br.readLine()) != null) {
// System.out.println(z++ + ": ");
String subLine = line.substring(5, line.length() - 2);
// System.out.println(subLine);
if (posList.contains(subLine)) {
System.out.println(count++ + " " + line);
fr1.write(line);
fr1.write("\n");
fr1.flush();
fr.close();
removeLineFromFile(inputFile.getAbsolutePath(), line);
}
}
br.close();
fr1.close();
writer.close();
} catch (Exception e) {
System.out.println("Exception caught : " + e);
}
}
static void removeLineFromFile(String file, String lineToRemove) {
try {
File inFile = new File(file);
//Construct the new file that will later be renamed to the original filename.
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String line = null;
//Read from the original file and write to the new
//unless content matches data to be removed.
while ((line = br.readLine()) != null) {
if (!line.trim().equals(lineToRemove)) {
pw.println(line);
pw.flush();
}
}
pw.close();
br.close();
//Delete the original file
if (!inFile.delete()) {
System.out.println("Could not delete file");
return;
}
//Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile)) {
System.out.println("Could not rename file");
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Can someone help me please?
String subLine = line.substring(5, line.length() - 2);
You are hard coding to take substring from index 5.
What happens when the length of line is less than 5? have a check if the line's length is less than 5 and only then proceed.
Also why are catching with 'Exception' ? try catching with a lower level exception like ArrayIndexOutOfBoundsException etc.
Thank you all for your help.
I figure out the problem, it was because I delete the file and create it again from temp file. in that case I lose the pointer to the file.
This is the code after I fix it if someone interested.
static void moveLines(ArrayList posList, int topic) {
//=======================To read lines=======
File inputFile = new File("U:\\Research\\Projects\\sef\\enhancfeaturtm\\Data1\\topic\\" + "Test" + topic + ".txt");
File outputFile = new File("U:\\Research\\Projects\\sef\\enhancfeaturtm\\Data1\\topic\\" + "Training" + topic + ".txt");
try {
FileReader fileReader = new FileReader(inputFile);
BufferedReader bufferedReader = new BufferedReader(fileReader);
FileWriter fileWriter = new FileWriter(outputFile);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
String line;
while ((line = bufferedReader.readLine()) != null) {
String subLine = line.substring(5, line.length() - 2);
if (posList.contains(subLine)) {
System.out.println(count++ + " " + line);
bufferedReader.close();
fileReader.close();
bufferedWriter.write(line+"\n");
bufferedWriter.flush();
bufferedReader = removeLineFromFile(inputFile.getAbsolutePath(), line);
}
}
bufferedWriter.close();
fileWriter.close();
bufferedReader.close();
fileReader.close();
} catch (Exception e) {
System.out.println("Exception caught : " + e);
}
}
static BufferedReader removeLineFromFile(String file, String lineToRemove) {
BufferedReader bufferedReader = null;
try {
File inFile = new File(file);
//Construct the new file that will later be renamed to the original filename.
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
BufferedReader br = new BufferedReader(new FileReader(file));
BufferedWriter bw = new BufferedWriter(new FileWriter(tempFile));
String line = null;
//Read from the original file and write to the new
//unless content matches data to be removed.
while ((line = br.readLine()) != null) {
if (!line.trim().equals(lineToRemove)) {
bw.write(line+"\n");
bw.flush();
}
}
bw.close();
br.close();
//Delete the original file
if (!inFile.delete()) {
System.out.println("Could not delete file");
return null;
}
//Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile)) {
System.out.println("Could not rename file");
}
FileReader fileReader = new FileReader(inFile);
bufferedReader = new BufferedReader(fileReader);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
return bufferedReader;
}

Java - Getting the line number of the text file that a BufferedWriter is writing to

File file = new File (directory + "Test.txt");
try {
BufferedWriter out = new BufferedWriter(new FileWriter(file, true));
out.write(in.read() + "This is a line of text.");
out.newLine();
out.close();
} catch (IOException e) {
}
I am trying to output the following into the text file. Let x represent the line number the BufferedWriter is writing to:
"x. This is a line of text."
But I have no clue as to how to do so and searched for quite a while. Any ideas? THANK YOU!
You can use in.readLine() method instead of in.read().
int linesCount = 0;
String currentLine = "";
while ((currentLine = in.readLine()) != null) {
linesCount++;
out.write(currentLine + "\n");
}

Using Buffered Reader and Writer to remove blank lines in a textfile; however I always leave the last line blank

I have a BufferedReaderand BufferedRriter that reads and removes blank lines from a textfile. It all works fine except I cannot for the life of me find a good solution to end it.
public static void cleanUpData(){
File inputFile = new File("C:\\Users\\student\\workspace\\EmployeePunch\\src\\EmployeeData.txt"); // Your file
File tempFile = new File("C:\\Users\\student\\workspace\\EmployeePunch\\src\\EmployeeDataNew.txt");// temp file
BufferedReader reader = null;
BufferedWriter writer = null;
try{
reader = new BufferedReader(new FileReader(inputFile));
writer = new BufferedWriter(new FileWriter(tempFile,true));
String currentLine;
while((currentLine = reader.readLine()) != null) {
if(currentLine.equals("")) continue;
writer.append(currentLine+"\n");
}
}
catch (IOException e) {
e.printStackTrace();
}finally{
try {
reader.close();
inputFile.delete();
writer.close();
boolean successful = tempFile.renameTo(inputFile);
System.out.println(successful);
validateEmployee();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
I know the reason it is doing it is being of the writer.append(currentLine+"\n"); but what would be another solution to stop at the last line?
Is there a way to know when I am right before the last line so to avoid using the +"\n"?
Don't add a newline after every output line. Instead, insert a a newLine before every line after the first line.
For example, you can replace your while loop with the following code:
boolean needsNewLine = false;
while((currentLine = reader.readLine()) != null) {
if(currentLine.equals("")) continue;
if (!needsNewLine) {
needsNewLine = true;
} else {
writer.append('\n');
}
writer.append(currentLine);
}

Reading/Writing Files in Java and Adding Line Numbers

I have the following assignment to complete:
Wrote a program that reads a file and writes a copy of the file to another file with line numbers inserted.
So far, I wrote the code that is posted below. This code reads and copies the text to another file, but I cannot figure out how to number each line in the new text file. Can someone please advise me on how to do so?
import java.io.*;
class FileCopy
{
public static void main(String[] args)
{
try
{
File fileIn = new File("Assign4.txt");
File fileOut = new File("target.txt");
FileInputStream streamIn = new FileInputStream(fileIn);
FileOutputStream streamOut = new FileOutputStream(fileOut);
int c;
while ((c = streamIn.read()) != -1)
{
streamOut.write(c);
}
streamIn.close();
streamOut.close();
}
catch (FileNotFoundException e)
{
System.err.println("FileCopy: " + e);
}
catch (IOException e)
{
System.err.println("FileCopy: " + e);
}
}
}
Thank you, I appreciate your help.
I will suggest BufferedReader (for sure) and PrintWriter. PrintWriter is a richer API compared to BufferedWriter.
You can you BufferedReader and BufferedReader to read and write text file:
BufferedReader br = new BufferedReader(new FileReader("Assign4.txt"));
BufferedWriter writer = new BufferedWriter( new FileWriter("target.txt"));
try {
int count = 1;
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(count++);
sb.append(line);
sb.append("\n");
writer.write(line);
line = br.readLine();
}
} finally {
br.close();
writer.close();
}

Categories

Resources