Advertisement
UrNotSorry

Java File I/O Example

Jul 20th, 2014
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.42 KB | None | 0 0
  1. import java.util.*;     // for Scanner class and a few other useful things
  2. import java.io.*;       // to enable reading and writing from files
  3.  
  4. public class FileIOExample {
  5.    
  6.     /* you need to include the "throws IOException" declaration
  7.      * because things may go wrong with the file I/O process
  8.      *
  9.      * unless you want to use try-catch statements
  10.      */
  11.     public static void main(String[] args) throws IOException {
  12.  
  13.         // this line opens a Scanner to read from your input file
  14.         // it reads just as if you were typing things into the console
  15.         Scanner input = new Scanner(new File("input.txt"));
  16.        
  17.         // this next line creates a file and allows you to print to it
  18.         // you use it like System.out.println()
  19.         PrintWriter out = new PrintWriter(new File("output.txt"));
  20.        
  21.         // for instance, if you want to read in a list of integers from a file...
  22.         List<Integer> list = new ArrayList<Integer>();
  23.         while (input.hasNextInt()) {
  24.             list.add(input.nextInt());
  25.         }
  26.        
  27.         // then, if you want to sort the numbers and print it back out to your file...
  28.         Collections.sort(list);
  29.         for (Integer i : list) {
  30.             out.println(i);     // just like printing to console...! without the System
  31.         }
  32.        
  33.         /* THESE NEXT TWO LINES ARE IMPORTANT... since you opened two files, one for reading and
  34.          * one for writing, you have to close those files so that it releases the resources
  35.          * back to your computer
  36.          */
  37.         input.close();
  38.         out.close();
  39.     }
  40.  
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement