LevSelector.com New York
home > Java input / Output

Java Input / Output
intro
cat
copy_in
copy_bin
copytext_test
copytext
tree
unicode
string_ex
string_out
socket client server
run external programs
intro home - top of the page -

File:
File a = new File("C:\\mydir");
File[] grp = a.listFiles( filter );   // filter is an object implementing the FileNameFilter interface
String[] names = a.list( filter);

if (a.exists( )) { }
if (a.isDirectory( )) { }
if (a.isFile( )) { }

Other methods:  exists( ), isDirectory( ), isFile( ), canRead( ),  canWrite( ),  long length( ),  long lastModified( ),  delete( ),  createNewFile( )

InputStream & OutputStream - abstract classes

FileInputStream, FileOutputStream - open file as a single-byte stream for reading/writing
ByteArrayInputStream, ByteArrayOutputStream - same, but you can read/write array of bytes.

Stream filters:
  DataInputStream & DataOutputStream - bytes to double
  BufferedInputStream & Buffered OutputStream
    PushbackInputStream

PrintStream class - traps all IOExceptions.
  Use PrintWriter instead

Interfaces DataOuput & DataInput:
   specify methods  void writeUTF(String s)   &    String readUTF( ).
   provide methods for reading/writing all of the java primitive types  (big-endian - most significant byte is written first - which opposite of what DOS/Windows is doing)

Reader & Writer - for reading chars, support locale:
BufferedReader,   BufferedWriter
CharArrayReader,  CharArrayWriter
FileReader , FileWriter ( = InputStreamReader + FileInputStream  ,  = OutputStreamWriter + FileOutputStream ).
InputStreamReader, OutputStreamWriter  (bridge between byte and char streams)
PrintWriter - Writer-derived analog to PrintStream class
LineNubmerReader - counts lines as it reads a stream

RandomAccessFile (File f, String mode);   //  mode = 'r'  or 'rw';
RandomAccessFile (String fname, String mode);

URL myurl = new URL (getDocumentBase(), "mydata.bin");
InputStream ins = myurl.openStream();


 
cat home - top of the page -

/**
*  read the file and output it on the console line-by-line
*/
import java.io.*;

public class cat {
 public static void main(String [] args) {
  String thisLine;
  for(int i=0; i<args.length;i++) {
   try {
    BufferedReader br = new BufferedReader(new FileReader(args[i]));
    while ((thisLine = br.readLine()) != null) {
     System.out.println(thisLine);
    } // end while
   } // end try
   catch (IOException e) {System.err.println("Error: " + e);}
  } // end for
 } // end main
}

 
copy_in home - top of the page -

/**
*  console utility to read lines from STDIN
*  and echo them back to the console
*/

import java.io.*;

public class copy_in {

 public static void main(String [] args) {
  String ss;
  while(true) {
   ss = getLine();
   ss = ss.trim();
   if (ss.charAt(0) == 'q') System.exit(0);
   System.out.println(ss);
  }
 } // end main
 

 /**
 * reads a line from STDIN
   */
 public static String getLine () {
  StringBuffer buf = new StringBuffer(80);
  int c;
  try {
   while ((c = System.in.read()) != -1) {
    char ch = (char) c;
    if (ch == '\n') break;
    buf.append(ch);
   }
  }
  catch (IOException e) {
   System.err.println(e);
  }
  return (buf.toString());
 }

}

 
copy_bin home - top of the page -

/**
  binary copy utility
  usage: java copybin <file_from> <file_to>
*/

import java.io.*;

public class copybin {

 public static void main(String [] args) {
  if (args.length != 2) {
   System.err.println("usage: java copybin infile outfile");
   System.out.println("Exiting.");
   System.exit(0);
  }
  try { copy(args[0], args[1]); }
  catch (IOException e) {System.err.println("Error: " + e); }
 }

 public static void copy(String inFile, String outFile)
  throws IOException {
   FileInputStream in = null;
   FileOutputStream out = null;
  try {
   in = new FileInputStream(inFile);
   out = new FileOutputStream(outFile);
   byte[]buffer = new byte[256];
   while (true) {
    int bytesRead = in.read(buffer);
    if (bytesRead == -1) break;
    out.write(buffer, 0, bytesRead);
   }
  }
  catch (IOException e) {}
  finally {
   try { if (in != null) in.close(); } catch (IOException e) {}
   try { if (out != null) out.close(); } catch (IOException e) {}
  }
 } // copy

}

 
copytext_test home - top of the page -

/**
  text copy (file names are hard coded)
*/
import java.io.*;

public class copytext_test {
  public static void main(String[] args) {
    try {
      File fout = new File("out.txt");
      PrintWriter out = new PrintWriter(new FileWriter(fout));

      BufferedReader in = new BufferedReader(new FileReader("in.txt"));
      String line;
      while((line=in.readLine()) != null) {
        out.println(line);
        System.out.println(line);
      }
      in.close();
      out.close();
    } catch (IOException e) {}
  }
}

 
copytext home - top of the page -

/**
  text copy utility
  usage: java copytext <file_from> <file_to>
*/

import java.io.*;

public class copytext {

 public static void main(String [] args) {

  if (args.length != 2) {
   System.out.println("usage java filecopy <file_from> <file_to>");
   System.out.println("Exiting.");
   System.exit(0);
  }

  String line;
  try {
   BufferedReader in = new BufferedReader(new FileReader(args[0]));
   PrintWriter out = new PrintWriter(new FileWriter(args[1]));
   while ((line = in.readLine()) != null) {
     out.println(line);
     System.out.println(line);
   } // end while
   in.close();
   out.close();
  } // end try
  catch (IOException e) {System.err.println("Error: " + e);}
 } // end main
}


 
tree home - top of the page -

import java.awt.*;
import java.io.File;

public class tree extends Frame {
 TextArea ta;

 public static void main(String [] args) {
  String path = ".";
  if(args.length>=1) path=args[0];

  File f = new File(path);
  if (! f.isDirectory()) {
   System.out.println("Doesn't exists or not dir " + path);
   System.exit(0);
  }

  tree tr = new tree(f);
  tr.setVisible(true);
 } // main

 tree(File f) {
  setSize(300,450);
  ta = new TextArea();
  ta.setFont(new Font("Monospaced", Font.PLAIN, 14));
  add(ta, BorderLayout.CENTER);
  recurse(f,0);
 }

 void recurse(File dirfile, int depth) {
  String contents[] = dirfile.list();
  for (int i=0; i<contents.length; i++) {
   for (int spaces=0; spaces<depth; spaces++)
    ta.append("-");
   ta.append(contents[i] + "\n");
   File child = new File(dirfile, contents[i]);
   if (child.isDirectory()) recurse(child, depth+1);
  }
 }

}

 
unicode home - top of the page -

public class unicode {

  public static void main(String [] args) {
  char c = '\uAAAA';
  Character cc = new Character(c);
  int ii = cc.hashCode();
  String hh = Integer.toHexString(ii);
  System.out.println("ii = " + ii + "  " + hh);
  }

}


 
string_ex home - top of the page -

public class string_ex{
 public static  void main(String arg[]){
  String str = new String("num\u3804ro");
   System.out.println(str);

  try{
   byte[] def = str.getBytes();
   byte[] utf = str.getBytes("Unicode");

   for (int i=0; i<def.length; i++){
    System.out.println("[" + i + "]:" + def[i]);
   }
   System.out.println("------");
   for (int i=0; i < utf.length; i++){
    System.out.println("[" + i + "]:" + utf[i]);
   }
   System.out.println("------");

   // Reconstruct strings
   String defstr = new String(def);
   String utfstr = new String(utf, "Unicode");
   System.out.println("default: " + defstr);
   System.out.println("utf8: " + utfstr);
  }
  catch(java.io.UnsupportedEncodingException e){
   e.printStackTrace();
  }
 }
}

 
string_out home - top of the page -

import java.io.*;

public class string_out {
  public static void main(String [] args) {
try{
 String str = "ir\u0438na";
 OutputStreamWriter out = new OutputStreamWriter( new FileOutputStream("irina"),"UnicodeBig");
 out.write(str);
 out.close();
}
catch (IOException e) {System.err.println("Error: " + e);}
  }
}


 
socket connection - client-server home - top of the page -

Read explanation here:
http://java.sun.com/docs/books/tutorial/networking/sockets/clientServer.html

Here is a digest:

Server: "Knock knock!"
Client: "Who's there?"
Server: "Dexter."
Client: "Dexter who?"
Server: "Dexter halls with boughs of holly."
Client: "Groan."

=========================================
server
=========================================
Socket clientSocket = null;
try {
    clientSocket = serverSocket.accept();
} catch (IOException e) {
    System.out.println("Accept failed: 4444");
    System.exit(-1);
}

PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
                        new InputStreamReader(
                            clientSocket.getInputStream()));
String inputLine, outputLine;

// initiate conversation with client
KnockKnockProtocol kkp = new KnockKnockProtocol();
outputLine = kkp.processInput(null);
out.println(outputLine);

while ((inputLine = in.readLine()) != null)
    outputLine = kkp.processInput(inputLine);
    out.println(outputLine);
    if outputLine.equals("Bye."))
        break;
}

out.close();
in.close();
clientSocket.close();
serverSocket.close();
 

=========================================
client:
=========================================
kkSocket = new Socket("taranis", 4444);
out = new PrintWriter(kkSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
                            kkSocket.getInputStream()));

while ((fromServer = in.readLine()) != null) {
    System.out.println("Server: " + fromServer);
    if (fromServer.equals("Bye."))
        break;
    fromUser = stdIn.readLine();
    if (fromUser != null) {
        System.out.println("Client: " + fromUser);
        out.println(fromUser);
    }
}

out.close();
in.close();
stdIn.close();
kkSocket.close();

=========================================

 
run external programs from java home - top of the page -

import java.io.*;

public class Test{

  public static void main(String args[]) {
    System.out.println("start");
    Process p = null;
    try {p=Runtime.getRuntime().exec("dir");}
      catch (java.io.IOException e){};
    try {p.waitFor();}
      catch (InterruptedException inte){};
    int stat = p.exitValue();
    System.out.println("finish with exit code: " + stat);
    System.out.println();
 

    BufferedReader br = new BufferedReader(
      new InputStreamReader(p.getInputStream())
    );
    StringBuffer sb = new StringBuffer();
    String line;
    try {
      while ((line = br.readLine()) != null)
        sb.append(line + "\r\n");
    } catch (java.io.IOException e){};
    System.out.println("output:");
    System.out.println(sb.toString());
  }

}