I'm stuck on writing to a specific line using File, BufferedReader, & BufferedWriter.
What I'm trying to achieve is getting my text files total line count (-3) & writing to that line.
Currently it just erases the whole file & nothing is written.
Image of what I'm doing:
(In Image) line 25 is blank & 26 doesn't contain a doc. it contains "}"
& My code:
package com.tests.writer;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JFrame;
public class NewWriter {
static Integer tableCount;
static File file;
static FileWriter fw;
static FileReader fr;
static BufferedWriter bw;
static BufferedReader br;
public static void main(String[] args) {
JFrame frame = new JFrame("Test {New Writer}");
frame.setBounds(500, 500, 500, 500);
frame.setVisible(true);
frame.setResizable(false);
frame.setAutoRequestFocus(true);
try {
startApplication();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void startApplication () throws IOException {
writeToFile ();
}
private static void writeToFile () throws IOException {
Integer lineTCount = 0;
file = new File("Tables.txt");
if (file.exists()) {
fw = new FileWriter(file.getAbsolutePath(), true);
fr = new FileReader(file.getAbsolutePath());
bw = new BufferedWriter(fw);
br = new BufferedReader(fr);
for (String line = br.readLine(); line != null; line = br.readLine()) {
lineTCount++;
System.out.println(lineTCount);
}
System.out.println(lineTCount);
bw.write("Test Text to insert");
System.out.println("done");
System.exit(0);
} else {
file.createNewFile();
System.out.println("New File = " + file.toString());
writeToFile();
}
}
}
If there is an easier way of doing this, I'm open to all idea's as I'm still not familiar with Java.io
& If anyone can tell me this is correct. I may have to add the whole file to a list, add the new text then re-write the file.