It might easily get complicated to read from and write to a text file if you don’t use the appropriate objects. What are these objects:
Here is the complete code:
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; public class Main { public static void main(String[] args) { readFile(); writeFile(); } // Reading from the text file public static void readFile() { BufferedReader br; try { br = new BufferedReader(new FileReader("C:\\test.txt")); String line = br.readLine(); while (line != null) { System.out.println(line); line = br.readLine(); } br.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } // Writing to the text file public static void writeFile() { PrintWriter pw = null; try { pw = new PrintWriter(new FileWriter("C:\\test2.txt")); } catch (IOException e) { e.printStackTrace(); } pw.print("content"); pw.close(); } }