Java Tutorial/File/FileInputStream

Материал из Java эксперт
Версия от 17:44, 31 мая 2010; (обсуждение)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Constructing FileInputStream to read from a Text File

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.nio.channels.FileChannel;
public class MainClass {
  public static void main(String[] a) {
    File aFile = new File("charData.txt");
    FileInputStream inFile = null;
    try {
      inFile = new FileInputStream(aFile);
    } catch (FileNotFoundException e) {
      e.printStackTrace(System.err);
      System.exit(1);
    }
    FileChannel inChannel = inFile.getChannel();
  }
}





Copy a file with read(byte[] data) and write(byte[] data)

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class Main {
  public static void main(String[] args) throws Exception {
    FileInputStream fin = null;
    FileOutputStream fout = null;
    File file = new File("C:/myfile1.txt");
    fin = new FileInputStream(file);
    fout = new FileOutputStream("C:/myfile2.txt");
    byte[] buffer = new byte[1024];
    int bytesRead;
    while ((bytesRead = fin.read(buffer)) > 0) {
      fout.write(buffer, 0, bytesRead);
    }
    fin.close();
    fout.close();
  }
}





Create FileInputStream and read, display data

import java.io.FileInputStream;
class FileInputStreamDemo {
  public static void main(String args[]) throws Exception {
    FileInputStream fis = new FileInputStream(args[0]);
    // Read and display data
    int i;
    while ((i = fis.read()) != -1) {
      System.out.println(i);
    }
    fis.close();
  }
}





Creating FileInputStream from File object

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class MainClass {
  public static void main(String[] a) {
    File aFile = new File("C:/myFile.txt");
    FileInputStream inputFile = null;
    try {
      inputFile = new FileInputStream(aFile);
    } catch (FileNotFoundException e) {
      e.printStackTrace(System.err);
      System.exit(1);
    }
  }
}





Creating File Input Streams from file name

import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class MainClass {
  public static void main(String[] a) {
    FileInputStream inputFile = null;
    try {
      inputFile = new FileInputStream("C:/myFile.txt");
    } catch (FileNotFoundException e) {
      e.printStackTrace(System.err);
    }
  }
}





Display file contents in hexadecimal

import java.io.FileInputStream;
public class Main {
  public static void main(String[] args) throws Exception {
    FileInputStream fis = new FileInputStream("/home/username/data.txt");
    int i = 0;
    int count = 0;
    while ((i = fis.read()) != -1) {
      if (i != -1) {
        System.out.printf("%02X ", i);
        count++;
      }
      if (count == 16) {
        System.out.println("");
        count = 0;
      }
    }
    fis.close();
  }
}





FileInputStream

  1. The FileInputStream class is a subclass of InputStream.
  2. The FileInputStream class allows you to read binary data sequentially from a file.
  3. The FileInputStream class"s constructors allow you to pass either a File object or a path to a file.



public FileInputStream (String path)
public FileInputStream (File file)





Getting FileChannel from FileInputStream

import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class MainClass {
  private static final int BSIZE = 1024;
  public static void main(String[] args) throws Exception {
    FileChannel fc = new FileInputStream("data.txt").getChannel();
    ByteBuffer buff = ByteBuffer.allocate(BSIZE);
    fc.read(buff);
    buff.flip();
    while (buff.hasRemaining())
      System.out.print((char) buff.get());
  }
}





Read bytes and display their hexadecimal values.

import java.io.FileInputStream;
public class Main {
  public static void main(String[] argv) throws Exception {
    FileInputStream fin = new FileInputStream("text.txt");
    int len;
    byte data[] = new byte[16];
    // Read bytes until EOF is encountered.
    do {
      len = fin.read(data);
      for (int j = 0; j < len; j++)
        System.out.printf("%02X ", data[j]);
    } while (len != -1);
  }
}





Read file character by character

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class Main {
  public static void main(String[] args) {
    File file = new File(args[0]);
    if (!file.exists()) {
      System.out.println(args[0] + " does not exist.");
      return;
    }
    if (!(file.isFile() && file.canRead())) {
      System.out.println(file.getName() + " cannot be read from.");
      return;
    }
    try {
      FileInputStream fis = new FileInputStream(file);
      char current;
      while (fis.available() > 0) {
        current = (char) fis.read();
        System.out.print(current);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}





Reading a Binary File

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class MainClass {
  public static void main(String[] args) {
    File aFile = new File("C:/test.bin");
    FileInputStream inFile = null;
    try {
      inFile = new FileInputStream(aFile);
    } catch (FileNotFoundException e) {
      e.printStackTrace(System.err);
    }
    FileChannel inChannel = inFile.getChannel();
    final int PRIMECOUNT = 6;
    ByteBuffer buf = ByteBuffer.allocate(8 * PRIMECOUNT);
    long[] primes = new long[PRIMECOUNT];
    try {
      while (inChannel.read(buf) != -1) {
        ((ByteBuffer) (buf.flip())).asLongBuffer().get(primes);
        for (long prime : primes) {
          System.out.printf("%10d", prime);
        }
        buf.clear();
      }
      inFile.close();
    } catch (IOException e) {
      e.printStackTrace(System.err);
    }
  }
}





Reading a File into a Byte Array: reads the entire contents of a file into a byte array

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class Main {
  public static void main(String[] argv) throws Exception {
    File file = new File("c:\\a.bat");
    InputStream is = new FileInputStream(file);
    long length = file.length();
    if (length > Integer.MAX_VALUE) {
      System.out.println("File is too large");
    }
    byte[] bytes = new byte[(int) length];
    int offset = 0;
    int numRead = 0;
    while (numRead >= 0) {
      numRead = is.read(bytes, offset, bytes.length - offset);
      offset += numRead;
    }
    if (offset < bytes.length) {
      throw new IOException("Could not completely read file " + file.getName());
    }
    is.close();
    System.out.println(new String(bytes));
  }
}





Reading into a Large Buffer through FileChannel

import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class MainClass {
  public static void main(String[] args) {
    try {
      test();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  private static void test() throws Exception {
    File aFile = new File("primes.txt");
    FileInputStream inFile = new FileInputStream(aFile);
    FileChannel inChannel = inFile.getChannel();
    ByteBuffer buf = ByteBuffer.allocateDirect(1024);
    buf.position(buf.limit());
    while (true) {
      if (buf.remaining() < 8) {
        if (inChannel.read(buf.rupact()) == -1){
          break;
        }
        buf.flip();
      }
      int strLength = (int) buf.getDouble();
      if (buf.remaining() < 2 * strLength) {
        if (inChannel.read(buf.rupact()) == -1){
          break;
        }
        buf.flip();
      }
      byte[] strChars = new byte[2 * strLength];
      buf.get(strChars);
      if (buf.remaining() < 8) {
        if (inChannel.read(buf.rupact()) == -1){
          break;
        }
        buf.flip();
      }
      System.out.println(strLength);
      System.out.println(ByteBuffer.wrap(strChars).asCharBuffer());
      System.out.println(buf.getLong());
    }
    inFile.close();
  }
}





Reading Mixed Data from a File

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class MainClass {
  public static void main(String[] args) {
    File aFile = new File("primes.txt");
    FileInputStream inFile = null;
    try {
      inFile = new FileInputStream(aFile);
    } catch (FileNotFoundException e) {
      e.printStackTrace(System.err);
    }
    FileChannel inChannel = inFile.getChannel();
    try {
      ByteBuffer lengthBuf = ByteBuffer.allocate(8);
      while (true) {
        if (inChannel.read(lengthBuf) == -1){
          break;
        }
        lengthBuf.flip();
        int strLength = (int) lengthBuf.getDouble();
        ByteBuffer buf = ByteBuffer.allocate(2 * strLength + 8);
        if (inChannel.read(buf) == -1) {
          break;
        }
        buf.flip();
        byte[] strChars = new byte[2 * strLength];
        buf.get(strChars);
        System.out.println(strLength);
        System.out.println(ByteBuffer.wrap(strChars).asCharBuffer());
        System.out.println(buf.getLong());
        lengthBuf.clear();
      }
      inFile.close();
    } catch (IOException e) {
      e.printStackTrace(System.err);
    }
  }
}





Reading UTF-8 Encoded Data

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class Main {
  public static void main(String[] argv) throws Exception {
    BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("infilename"),
        "UTF8"));
    String str = in.readLine();
    System.out.println(str);
  }
}





Read one byte from a file

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Main {
  public void readOneByte() throws FileNotFoundException {
    FileInputStream file = null;
    byte x = -1;
    try {
      file = new FileInputStream("fileName");
      x = (byte) file.read();
    } catch (FileNotFoundException f) {
      throw f;
    } catch (IOException i) {
      i.printStackTrace();
    } finally {
      try {
        if (file != null) {
          file.close();
        }
      } catch (IOException e) {
      }
    }
  }
}





Skip n bytes while reading the file using FileInputStream

import java.io.File;
import java.io.FileInputStream;
public class Main {
  public static void main(String[] args) throws Exception {
    File file = new File("C:/String.txt");
    FileInputStream fin = new FileInputStream(file);
    int ch;
    // skip first 10 bytes
    fin.skip(10);
    while ((ch = fin.read()) != -1){
      System.out.print((char) ch);
    }
  }
}





Using a FileDescriptor from getFD() and creating a FileInputStream from FileDescriptor

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
public class MainClass {
  public static void main(String[] a) {
    File aFile = new File("C:/myFile.text");
    FileInputStream inputFile1 = null; 
    FileDescriptor fd = null; 
    try {
      inputFile1 = new FileInputStream(aFile);
      fd = inputFile1.getFD(); 
    } catch (IOException e) {
      e.printStackTrace(System.err);
      System.exit(1);
    }
    FileInputStream inputFile2 = new FileInputStream(fd);
  }
}