//方法一(每次只读取一个字节) public static void getFile() throws IOException { File file = new File("D:\a.txt"); FileInputStream fileinputstream = new FileInputStream(file); int data = fileinputstream.read(); int data1 = fileinputstream.read(); System.out.println("获取的数据"+data1); fileinputstream.close(); }
只是输出目标文件的第一个字符,所以说很不实用
//方法二 public static void getFile2() throws IOException { File file = new File("D:\a.txt"); FileInputStream fileInputStream = new FileInputStream(file); for (int i = 0; i <file.length(); i++) { System.out.print((char)fileInputStream.read()); } fileInputStream.close(); }
通用步骤:
1.找到目标文件:注意操作的是文件而不是文件夹(切记!!!!!)
2.建立通道
3.[创建缓冲区]
4.读取数据:read()只获取一个字节
5.释放之原文件
需要不断地运行一个循环内存占用过大
public static void getFile3() throws IOException { File file = new File("D:\a.txt"); FileInputStream fileInputStream = new FileInputStream(file); byte[] b = new byte[(int) file.length()]; int count = fileInputStream.read(b); System.out.println(count); System.out.println(new String(b)); fileInputStream.close(); }
public static void getFile4() throws IOException { File file = new File("D:\java\第十八次课\代码\Day18\src\com\beiwo\File\Demo1.java"); FileInputStream fileInputStream = new FileInputStream(file); byte[] b = new byte[1024]; int count = 0; while ((count = fileInputStream.read(b))!= -1) { System.out.println(new String(b,0,count)); } fileInputStream.close(); }
终极版