Files

Binary files

 








Text files











For example, the SampleFile which contains

ABC 123
DEF 456
GHI 789

consists of the following ASCII codes:
csc% od -t u1 SampleFile 
0000000 65  66  67  32  49  50  51  10  68  69  70  32  52  53  54  10
0000020 71  72  73  32  55  56  57  10
0000030


         A   B   C  sp   1   2   3  \n   D   E   F  sp   4   5   6  \n
	 G   H   I  sp   7   8   9  \n












Input Files

To get a "input" from a file, we need to:

1.


2.



3.



Output Files

To "output" data to a file, we need to:

1.



2.



3.



Input File Example

import java.io.*;

public class Input {
  
  public static void main(String[] args) { 
  
    BufferedReader br;
    
    //Try to open the SampleFile, read each line, and close the file
    try {
      
      //Open an input file called SampleFile
      br = new BufferedReader (new FileReader ("SampleFile"));
      
      //While we're not at the end of the file, read each line
      //and output it to the terminal
      
      String line;
      
      while ( (line = br.readLine()) != null)
        
	System.out.println(line); 
	
      br.close();
      
    }
    
    //Catch any file problems that may occur
    catch (IOException e) {
    
    //Tell what went wrong and exit with status of 1
      System.err.println("File error: " + e);
      System.exit(1);
      
    }
  }
}

OUTPUT:

csc% java Input
ABC 123
DEF 456
GHI 789




    
   

Output File Example

import java.io.*;

public class Output {

  public static void main(String[] args) {
  
    PrintWriter pw;
    
    //Try to open the OutputFile, 
    //output the numbers from 1 to 10 one per line, and close the file
    try {
    
      //Open a file called OutputFile
      pw = new PrintWriter(new FileWriter("OutputFile"));
      
      //Output the numbers from 1 to 10 to the file, one per line,
      //preceded and followed by < and >
      final int MAX = 10;
      for (int i = 1; i <= MAX; i++)
        pw.println("<" + i + ">");
	
      //Close the file - very important for output files
      pw.close();
    } 
     
    //Catch any problems that may occur
    catch(IOException e) {
      //Tell what went wrong
      System.err.println("File error: " + e);
      //And exit with status of 1
      System.exit(1);
    }
  }
}

CONTENTS OF OutputFile:

csc% cat OutputFile
<1>
<2>
<3>
<4>
<5>
<6>
<7>
<8>
<9>
<10>