Use System.in
Use BufferedReader
Use read method
File Handling
Reading from a File
Use FileInputSt ream
Use read method
Writ ing to a File
Use FileOutputSt ream
Use write method
Sample program to input a textfile and display its contents import java.io.*; public class RFile { public static void main(String args[]) throws IOException { System.out.println("What is the name of the file to read from?"); String filename; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); filename = br.readLine(); System.out.println("Now reading from " + filename + "..."); FileInputStream fis = null; try { fis = new FileInputStream(filename); } catch (FileNotFoundException ex) { System.out.println("File not found."); } try { char data; int temp; do { temp = fis.read(); data = (char) temp; if (temp != -1) { System.out.print(data); } } while (temp != -1); System.out.println(); } catch (IOException ex) { System.out.println("Problem in reading from the file.");
}
}
}
Sample program to input a textfile and input any text and save it in that text file
import java.io.*; public class WFile { public static void main(String args[]) throws IOException { System.out.print("What is the name of the file to be written to? "); String filename; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); filename = br.readLine(); System.out.println("Enter data to write to " + filename + "..."); System.out.println("Type q$ to end."); FileOutputStream fos = null; try { fos = new FileOutputStream(filename); } catch (FileNotFoundException ex) { System.out.println("File cannot be opened for writing."); } try { boolean done = false; int data; do { data =