package com.yang;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class FileDemo1 {
public static void main(String[] args) throws IOException {
1.读取文件内容的第一种方法 单个字节进行读取
String filePath = “D:\yangshen\h1.txt”;
File file = new File(filePath);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(filePath);
while ((readData = fileInputStream.read())!= -1) {
System.out.print((char)readData);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
fileInputStream.close();
}
2.读取文件内容的第一种方法 多个字节进行读取
byte[] bytes = new byte[6];//一次读取四个字节
FileInputStream fileInputStream = null;
fileInputStream = new FileInputStream(filePath);
int readLen = fileInputStream.read(bytes);
System.out.println(readLen);//第一次读取到了6个字节
readLen = fileInputStream.read(bytes);
System.out.println(readLen);//第二次读取到了2个字节
3.读取文件内容的最终版
String filePath = "D:\\yangshen\\h1.txt";
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(filePath);
byte[] bytes = new byte[4];//每一次读取四个字节
int readCount = 0;
while ((readCount = fileInputStream.read(bytes)) != -1) {
System.out.print(new String(bytes,0,readCount));//将字节数组转换为字符串
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
fileInputStream.close();
}
}
}
相关文章
暂无评论...