Skip to main content

HOW TO INTERFACE WITH FILES IN JAVA

Simple example to use string in different ways.

Syntax :

String variable_name = "Hello World!"

Example :

  1. import java.io.*; 
  2. public class CopyFile {
  3.    public static void main(String args[]) throws IOException
  4.    {
  5.       FileInputStream in = null;
  6.       FileOutputStream out = null;
  7.        try {
  8.          in = new FileInputStream("input.txt");
  9.          out = new FileOutputStream("output.txt");
  10.         
  11.          int c;
  12.          while ((c = in.read()) != -1) {
  13.             out.write(c);
  14.          }
  15.       }finally {
  16.          if (in != null) {
  17.             in.close();
  18.          }
  19.          if (out != null) {
  20.             out.close();
  21.          }
  22.       }
  23.    }
  24. }

Description :

Step 1:Starting of class
Step 2:Start of main function.
Step 3:The input or output type of exceptions that occur in main function are thrown away.
Step 4 :There are many classes for byte stream but FileInputStream and FileOutputStream are most frequently used. Here input.txt is the name of actual file that is present in your machine.
Step 5:Here output.txt is the file that will be created .
Step 12: Read every character from file "input,txt" .
Step 13:Write every character in file "output.txt" .
Step 15 - 18: "finally" keyword is used when all try catch operations are completed. If input,txt not closed then in.close closes input.txt file. Same for output.txt file,