Writing data to a text file in Java

There are several ways, in this example we show you one of them using the FileWriter wrapped into a BufferedWriter, that is wrapped into a PrintWriter to allow you to use the println() methods that are easy to use.

import java.io.*;
 
public class Main {
   public static void main(String []args) {
      try {
         String line;
         BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"));
         PrintWriter pw = new PrintWriter(bw);
         pw.println("Esus");
         pw.println(true);
         pw.println('a');
         pw.write("Esus.com", 5, 3);
         pw.close();
      }
      catch (IOException e) {
         System.out.println(e);
      }
   }
}

Check out the API’s for more information on the print methods you can use!

Reading data from a text file in Java

If you are reading a text file, you can use the FileReader class in the java.io package. Here’s an example:

import java.io.*;
 
public class Main {
   public static void main(String []args) {
      if (args.length != 1) {
         System.out.println("Usage: java Main <textfile>");
         System.exit(1);
      }
  
      try {
         String line;
         BufferedReader br = new BufferedReader(new FileReader(args[0]));
         while ((line = br.readLine()) != null) {
            System.out.println(line);
         }
      }
      catch (IOException e) {
         System.out.println(e);
      }
   }
}

You will probably still see code around that uses the method readLine of the DataInputStream class. Sun has deprecated this method because it does not properly convert bytes (1 byte) to characters (2 bytes). Here’s the code if you’re still using 1.0.2:

import java.io.*;
 
public class Main {
   public static void main(String []args) {
      if (args.length != 1) {
         System.out.println("Usage: java Main <textfile>");
         System.exit(1);
      }
  
      try {
         String line;
         DataInputStream dis = new DataInputStream(new FileInputStream(args[0]));
         while ((line = dis.readLine()) != null) {
            System.out.println(line);
         }
      }
      catch (IOException e) {
         System.out.println(e);
      }
   }
}

Detecting CAPS LOCK in Java

From JDK1.3, you should normally be able to get the state using the Toolkit class as shown in following example.

Main.java

import java.awt.*;
 
public class Main
{
   public static void main(String []args) {
      Toolkit tk = Toolkit.getDefaultToolkit();
      System.out.println(tk.getLockingKeyState(java.awt.event.KeyEvent.VK_CAPS_LOCK));
 
      System.exit(1);
   }
}

However, check out this bug.

Reading an int from standard input

Wrap System.in in a BufferedReader object and call the method readLine. Then convert that string to an int.
Main.java:

import java.io.*;
 
public class Main 
{
   public static void main(String [] args) {
      BufferedReader stdin = new BufferedReader
         (new InputStreamReader(System.in));
      String number;
  
      System.out.println ("Enter a integer number:");
      try {
         number = stdin.readLine();
         int n = Integer.parseInt(number);
         System.out.println("You entered " + n);
      }
      catch(Exception e) {
         System.out.println("You did not enter a valid number!");
      }
   } 
} 

How do I read from standard input?

Standard input (stdin) is represented by System.in. System.in is an instance of the class java.io.InputStream. This means that all its methods work on bytes, not Strings.
To read from keyboard, use the Reader classes provided since JDK 1.1 They provide unicode manipulation.
Following is an example that reads in 2 Strings from stdin, converts them to integers and displays the multiplication of the two.

import java.io.*; 
 
public class Multiply { 
 
   public static void main (String[] args) { 
      int firstNum, secondNum, result;
 
      //  open up standard input 
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
 
      try { 
         System.out.print("Enter first number: "); 
         firstNum = Integer.parseInt(br.readLine());
         System.out.print("Enter second number: "); 
         secondNum = Integer.parseInt(br.readLine());
         result = firstNum * secondNum;
 
         System.out.println("The multiplication is " + result); 
      } catch (IOException e) { 
         System.out.println(e);
      } 
   } 
}  

Redirecting System.out to a file

Instantiate a PrintStream that streams to your file and use the System.setOut method.
The same can be done for the input and error streams (setIn and setErr).

import java.io.*;
 
public class Main
{
   public static void main(String args[]) {
      try {
         BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("log"));
         PrintStream ps = new PrintStream(bos);
         System.setOut(ps);
 
         System.out.println(&quot;Hello world!&quot;);
 
         ps.close();
      }
      catch(FileNotFoundException e) {
         System.out.println(e);
      }
   }
}

Displaying binary, hexadecimal or octal values

Use one of the following static methods to convert integers
into binary, hexadecimal or octal string representations:

Integer.toBinaryString(int)
Integer.toHexString(int)
Integer.toOctalString(int)

For bigger values use:

Long.toBinaryString(int)
Long.toHexString(int)
Long.toOctalString(int)

For arbitrary precision integers use
BigInteger.toString(int radix) with the values 2 (binary),
16 (hexadecimal) and 8 (octal).

Using a PipedReader and PipedWriter

A pipe is a communication channel between two threads. It is typically used in producer-consumer systems where one thread produces data (producer) necessary for the other thread (consumer) to operate. In Java, a pipe is implemented by connecting a PipedReader instance to a PipedWriter instance:

   PipedWriter producer = new PipedWriter();
   PipedReader consumer = new PipedReader(producer);

All data written to producer will be stored in a pipe (buffer) until the consumer reads it.

In this example, a thread mimics the behavior of scores for 10 contestants coming in by generating random numbers between [0, 10[. Another thread keeps track of the total votes per contestant.

Main.java:

import java.util.*;
import java.io.*;
 
public class Main {   
   public static void main(String[] args) throws Exception {
      PipedWriter producer = new PipedWriter();
      PipedReader consumer = new PipedReader(producer);
 
      NumberProducer np = new NumberProducer(producer);
      NumberConsumer nc = new NumberConsumer(consumer);
 
      np.start();
      nc.start();
   }
}
 
class NumberProducer extends Thread
{
   BufferedWriter bw;
 
   public NumberProducer(Writer w) {
      this.bw = new BufferedWriter(w);
   }
 
   // thread continually produces random votes
   public void run() {
      try {
         Random r = new Random();
         while (true) {
            String vote = "" + Math.abs((r.nextInt() % 10));
 
            bw.write(vote);
            bw.newLine();
            bw.flush();
 
            sleep(10);
         }  
      }   
      catch(IOException e) {
         System.err.println(e);
      }
      catch(InterruptedException e) {
         System.err.println(e);
      }      
   }
}
 
class NumberConsumer extends Thread
{
   BufferedReader br;
   int[] votes = new int[10];
  
   public NumberConsumer(Reader r) {
      br = new BufferedReader(r);
   }
 
   public void run() {
      try {
         String line;
         int count = 0;
         while ((line = br.readLine()) != null) {
            int contestant = Integer.parseInt(line);
            votes[contestant]++;
 
            count++;
            if (count % 100 == 0) 
               printVotes();
         }      
      }   
      catch(IOException e) {
         System.err.println(e);
      }
   }
 
   public void printVotes() {
      for (int i=0; i<votes.length; i++) {
         System.out.println("Contestant #" + i + ": " + votes[i]);
      }
      System.out.println("——————");
   }
}

outputs:

Contestant #0: 7
Contestant #1: 8
Contestant #2: 10
Contestant #3: 15
Contestant #4: 5
Contestant #5: 11
Contestant #6: 4
Contestant #7: 15
Contestant #8: 16
Contestant #9: 9
------------------
Contestant #0: 22
Contestant #1: 22
Contestant #2: 26
Contestant #3: 21
Contestant #4: 11
Contestant #5: 18
Contestant #6: 13
Contestant #7: 26
Contestant #8: 26
Contestant #9: 15
------------------
Contestant #0: 32
Contestant #1: 29
Contestant #2: 37
Contestant #3: 30
Contestant #4: 29
Contestant #5: 31
Contestant #6: 22
Contestant #7: 35
Contestant #8: 34
Contestant #9: 21
------------------
. . .

Converting a String to a Reader

Java provides a StringReader class expressly for this purpose. java.io.StringReader has a constructor that takes a String argument.

import java.io.StringReader;
...
String myString = 'Testing 1 2 3...';
StringReader myStringReader = new StringReader(myString);
 
// Then, use standard Reader-reading techniques
// to access the Reader
int len = -1; // Number of chars read
char [] buf = new char[256]; // Characters read from Reader
try { 
   while ((len = myStringReader.read(buf, 0, 256)) != -1) {
      System.out.println('Next chunk from Reader is ' + (new String(buf, 0, len)));
   }
} catch (IOException ioe) {
   System.err.println("Error reading from Reader :" + e.getMessage());
}