I'm trying to make two objects that are able to read and write to a text file. The problem happens when I execute the program. The text file gets erased. Why is this happening and how do I fix this?
CODE:
Object to read text files:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Reader {
public static String fromFile;
public static FileReader fr;
public static BufferedReader file;
public Reader(String fileName) throws IOException, FileNotFoundException {
fr = new FileReader(fileName);
file = new BufferedReader(fr);
}
public void readFile() throws IOException {
while((fromFile = file.readLine()) != null) {
System.out.println(fromFile);
}
}
}
Object to write to text files:
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
public class Writer {
public static FileWriter fw;
public static BufferedWriter file;
public Writer(String fileName) throws IOException, FileNotFoundException {
fw = new FileWriter(fileName);
file = new BufferedWriter(fw);
}
}
Main method to create Reader and Writer objects and use the Reader to read the text file:
import java.io.IOException;
public class Main {
public static Writer toFile;
public static Reader fromFile;
public static String fileName = "test123.txt";
public static void main(String[] args) throws IOException {
toFile = new Writer(fileName);
fromFile = new Reader(fileName);
fromFile.readFile();
}
}