Advertisement
yo2man

Tutorial 40 Creating and Writing Text Files

May 25th, 2015
253
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.10 KB | None | 0 0
  1.  
  2. //Tutorial 40 Creating and Writing Text Files
  3. //code for reading a file and writing a file is almost identical
  4. //but instead of using a BufferedReader, you use a BufferedWriter and instead of a FileReader you use a FileWriter
  5.  
  6.  
  7. import java.io.BufferedWriter;
  8. import java.io.File;
  9. import java.io.FileWriter;
  10. import java.io.IOException;
  11.  
  12. public class App {
  13.  
  14.     public static void main(String[] args) {
  15.         File file = new File("test.txt");
  16.  
  17.         try (BufferedWriter br = new BufferedWriter(new FileWriter(file))) {
  18.    
  19.             br.write("This is line one");
  20.             br.newLine();
  21.             br.write("This is line two");
  22.             br.newLine();
  23.             br.write("Last line.");
  24.            
  25.         } catch (IOException e) {
  26.             System.out.println("Unable to read file " + file.toString());
  27.         }
  28.  
  29.  
  30.     }
  31.  
  32. }
  33. //---------------------------------------------------------------------------------------------------------------------------------------
  34. /* Run Results:
  35. blank
  36. */
  37. // a new "test.txt" file should be created with the words:
  38. /*
  39. This is line one
  40. This is line two
  41. Last line.
  42. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement