我们可以构造一个文件输入流,然后再利用read方法读取文件中的一个字节:
1 package com.hw.file0205; 2 3 import java.io.FileInputStream; 4 import java.io.FileNotFoundException; 5 import java.io.IOException; 6 7 public class TestInputStream { 8 public static void main(String[] args) { 9 FileInputStream input = null; //创建文件输入流,这里先赋值为null 10 try { 11 input = new FileInputStream("F://骚操作//something.txt"); 12 int a = input.read(); //读取该文件中的一个字节。 13 System.out.println((char)a); 14 }catch (IOException e) { 15 // TODO Auto-generated catch block 16 e.printStackTrace(); 17 }finally{ 18 try { 19 if(input != null){ 20 input.close(); //要记得关闭! 21 } 22 23 } catch (IOException e) { 24 // TODO Auto-generated catch block 25 e.printStackTrace(); 26 } 27 } 28 } 29 }
我的这个文件是这样的:
此外,这份代码里面有很多try-catch语句,建议有的话当场解决,不要遇到就抛。