Java Tutorial/File/FileInputStream
Содержание
- 1 Constructing FileInputStream to read from a Text File
- 2 Copy a file with read(byte[] data) and write(byte[] data)
- 3 Create FileInputStream and read, display data
- 4 Creating FileInputStream from File object
- 5 Creating File Input Streams from file name
- 6 Display file contents in hexadecimal
- 7 FileInputStream
- 8 Getting FileChannel from FileInputStream
- 9 Read bytes and display their hexadecimal values.
- 10 Read file character by character
- 11 Reading a Binary File
- 12 Reading a File into a Byte Array: reads the entire contents of a file into a byte array
- 13 Reading into a Large Buffer through FileChannel
- 14 Reading Mixed Data from a File
- 15 Reading UTF-8 Encoded Data
- 16 Read one byte from a file
- 17 Skip n bytes while reading the file using FileInputStream
- 18 Using a FileDescriptor from getFD() and creating a FileInputStream from FileDescriptor
Constructing FileInputStream to read from a Text File
<source lang="java">
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(); }
}</source>
Copy a file with read(byte[] data) and write(byte[] data)
<source lang="java">
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(); }
}</source>
Create FileInputStream and read, display data
<source lang="java">
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(); }
}</source>
Creating FileInputStream from File object
<source lang="java">
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); } }
}</source>
Creating File Input Streams from file name
<source lang="java">
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); } }
}</source>
Display file contents in hexadecimal
<source lang="java">
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(); }
}</source>
FileInputStream
- The FileInputStream class is a subclass of InputStream.
- The FileInputStream class allows you to read binary data sequentially from a file.
- The FileInputStream class"s constructors allow you to pass either a File object or a path to a file.
<source lang="java">
public FileInputStream (String path) public FileInputStream (File file)</source>
Getting FileChannel from FileInputStream
<source lang="java">
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()); }
}</source>
Read bytes and display their hexadecimal values.
<source lang="java">
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); }
}</source>
Read file character by character
<source lang="java">
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(); } }
}</source>
Reading a Binary File
<source lang="java">
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); } }
}</source>
Reading a File into a Byte Array: reads the entire contents of a file into a byte array
<source lang="java">
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)); }
}</source>
Reading into a Large Buffer through FileChannel
<source lang="java">
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(); }
}</source>
Reading Mixed Data from a File
<source lang="java">
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); } }
}</source>
Reading UTF-8 Encoded Data
<source lang="java">
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); }
}</source>
Read one byte from a file
<source lang="java">
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) { } } }
}</source>
Skip n bytes while reading the file using FileInputStream
<source lang="java">
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); } }
}</source>
Using a FileDescriptor from getFD() and creating a FileInputStream from FileDescriptor
<source lang="java">
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); }
}</source>