Examples of working with Java input/output system (according to the book OOP: Objects, Java, and Aspects)


Directory contents

import java.io.*;
import java.util.*;

public class Dir {
   public static void main(String[] args) {
      File path = new File(".");
      String[] list;
      list = path.list();
      for(int i = 0; i < list.length; i++)
        System.out.println(list[i]);
   }
}


Filtered directory contents

import java.io.*;
import java.util.*;

public class FDir {
   public static void main(String[] args) {
      File path = new File(".");
      String[] list;
      list = path.list(new XFilter());
      for(int i = 0; i < list.length; i++)
         System.out.println(list[i]);
   }
}
class XFilter implements FilenameFilter {
   public boolean accept(File dir, String name) {
      return name.charAt(0) == 'x';
   }
}



The java.io package should be imported into all following examples (import java.io.*;).


Reading a file by lines

public class Subor {
   public static void main(String[] args) throws IOException {
      BufferedReader in = new BufferedReader(new FileReader("src/Subor.java")); // correct according to where the source file is placed
      String r, s = new String();

      while ((r = in.readLine()) != null)
         s += r + "\n";

      in.close();
   }
}


Reading the standard input

public class C {
   public static void main(String[] args) throws IOException {
      BufferedReader stdin =
         new BufferedReader(new InputStreamReader(System.in));

      System.out.print("Vstup: ");
      String s = stdin.readLine();
      System.out.println(s);
   }
}


Standard input and Scanner

import java.io.*;
import java.util.*;

public class C {
   public static void main(String[] args) throws IOException {
      Scanner sc = new Scanner(System.in);
      System.out.print("Street and number: ");

      String street = sc.next();
      int number = sc.nextInt();

      sc.close();

      System.out.println("Street: " + street);
      System.out.println("Number: " + number);
   }
}


Formatted input

public class C {
   public static void main(String[] args) throws IOException {
      double a = 10000.0;
      System.out.printf("a = %e%n", a);
   }
}


Reading from the memory by characters

public class C {
   public static void main(String[] args) throws IOException {
      String s = new String("12356789");
      StringReader in = new StringReader(s);

      int c;
      while ((c = in.read()) != -1)
         System.out.print((char)c);
      in.close();
   }
}


Reading from the memory by the data format

public class C {
   public static void main(String[] args) throws IOException {
      String s = new String("123456789");
      DataInputStream in = null;
      try {
         in = new DataInputStream(new ByteArrayInputStream(s.getBytes()));

         while (true)
            System.out.print((char)in.readByte());
      } catch(EOFException e) {
         System.err.println("\nEnd of stream");
      } finally {
         in.close();
      }
   }
}


File output

public class C {
   public static void main(String[] args) throws IOException {
      String s = new String("123\nabc");
      BufferedReader in = null;
      PrintWriter out = null;
      
      try {
         in = new BufferedReader(new StringReader(s));
         out = new PrintWriter(new BufferedWriter(new FileWriter("demo.out")));
         int l = 1;
         while ((s = in.readLine()) != null )
            out.println(l++ + ": " + s); // c. riadku: obsah
      } catch(EOFException e) {
         System.err.println("Koniec prúdu");
      } finally {
         in.close();
         out.close();
      }
   }
}


Storing and loading data

public class C {
   public static void main(String[] args) throws IOException {
      DataOutputStream out = null;
      DataInputStream in = null;
      
      try {
         out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("data.txt")));

         out.writeUTF("Text");
         out.writeDouble(1.1);
         
         out.close();

         in = new DataInputStream(new BufferedInputStream(new FileInputStream("data.txt")));

         System.out.println(in.readUTF());
         System.out.println(in.readDouble());
      } catch(EOFException e) {
         throw new RuntimeException();
      } finally {
         in.close();
         out.close();
      }
   }
}


Random access files

public class C {
   public static void main(String[] args) throws IOException {
      RandomAccessFile f =
         new RandomAccessFile("test.dat", "rw");
    
      for(int i = 0; i < 10; i++)
         f.writeInt(i);
      
      f.seek(3*4); // set the position after the third int
      f.writeInt(-1);
          
      f.seek(0); // set the position at the beginning
      for(int i = 0; i < 10; i++)
         System.out.println(i + ": " + f.readInt());
      f.close();
   }
}


Channels and buffers

import java.io.*;
import java.nio.*;
import java.nio.channels.*;

public class C {
   public static void main(String[] args) throws Exception {
      FileChannel fc = new FileOutputStream("data.txt").getChannel();
      fc.write(ByteBuffer.wrap("Some text ".getBytes()));
      fc.close();
   }
}


Memory mapped files

import java.io.*;
import java.nio.*;
import java.nio.channels.*;

public class C {
   static int length = 0x6400000; // 100 MiB
   
   public static void main(String[] args) throws Exception {
      MappedByteBuffer out = 
         new RandomAccessFile("test.dat", "rw").getChannel().
            map(FileChannel.MapMode.READ_WRITE, 0, length);
      
      for(int i = 0; i < length; i++)
         out.put((byte)((65 + i) % 128));

      for(int i = length/2; i < length/2 + 6; i++)
         System.out.print((char)out.get(i));
   }
}


Valentino Vranić
vranic at stuba.sk