Classwork Demo (03-03-2022)
unknown
java
3 years ago
1.9 kB
30
Indexable
Never
import java.io.*; import java.util.Scanner; //import java.io.PrintWriter; public class Week5Extra { public static void main (String[] args) { /* * Java PrintWriter Documentation: * https://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html#println() */ /* Writing output to a text file using PrintWriter */ try { PrintWriter file_handler = new PrintWriter("output.txt"); file_handler.println("Sample text 1"); file_handler.println("Sample text 2"); file_handler.close(); } catch(Exception e){ // e.printStackTrace(); System.out.println("[!] Error occured while writing file"); System.exit(1); } // try { // PrintWriter fh = new PrintWriter( new BufferedWriter( // new FileWriter("output.txt", true))); // 2nd parameter set to true // // allows appending to text file // fh.append("Sample text 3\n"); // fh.append("Sample text 4\n"); // fh.close(); // } catch(Exception e){ // // e.printStackTrace(); // System.out.println("[!] Error occured while writing file"); // System.exit(1); // } /* Reading from file */ // try { // Scanner scan_file = new Scanner(new File("sample-cars.txt")); // while (scan_file.hasNext()){ // System.out.println(scan_file.nextLine()); // } // scan_file.close(); // } catch (Exception e){ // // e.printStackTrace(); // System.out.println("[!] Error occured while reading file"); // System.exit(1); // } } }