java 四种方式读取文件

时间:2021-03-20 17:20:01

在学习java读取文件之间,应该先了解一下java读写文件常用的几种流,具体看本人博客http://www.cnblogs.com/Zchaowu/p/7353348.html

读取文件的四种方式:按字节读取、按字符读取、按行读取、随机读取

 

一、按字节读取

//1.按字节读写文件,用FileInputStream、FileOutputStream
String path = "D:\\iotest.txt";
File file
= new File(path);
InputStream in;
//每次只读一个字节
try {
System.out.println(
"以字节为单位,每次读取一个字节");
in
= new FileInputStream(file);
int c;
while((c=in.read())!=-1){
if(c!=13&&c!=10){ // \n回车的Ascall码是10 ,\r换行是Ascall码是13,不现实挥着换行
System.out.println((char)c);
}
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}

//每次读多个字节
try {
System.out.println(
"以字节为单位,每次读取多个字节");
in
= new FileInputStream(file);
byte[] bytes = new byte[10]; //每次读是个字节,放到数组里
int c;
while((c=in.read(bytes))!=-1){
System.out.println(Arrays.toString(bytes));
}
}
catch (Exception e) {
// TODO: handle exception
}

 

二、按字符读取

//2.按字符读取文件,用InputStreamReader,OutputStreamReader
Reader reader = null;
try {//每次读取一个字符
System.out.println("以字符为单位读取文件,每次读取一个字符");
in
= new FileInputStream(file);
reader
= new InputStreamReader(in);
int c;
while((c=reader.read())!=-1){
if(c!=13&&c!=10){ // \n回车的Ascall码是10 ,\r换行是Ascall码是13,不现实挥着换行
System.out.println((char)c);
}
}
}
catch (Exception e) {
// TODO: handle exception
}

try {//每次读取多个字符
System.out.println("以字符为单位读取文件,每次读取一个字符");
in
= new FileInputStream(file);
reader
= new InputStreamReader(in);
int c;
char[] chars = new char[5];
while((c=reader.read(chars))!=-1){
System.out.println(Arrays.toString(chars));
}
}
catch (Exception e) {
// TODO: handle exception
}

 

三、按行读取

//3.按行读取文件
try {
System.out.println(
"按行读取文件内容");
in
= new FileInputStream(file);
Reader reader2
= new InputStreamReader(in);
BufferedReader bufferedReader
= new BufferedReader(reader2);
String line;
while((line=bufferedReader.readLine())!=null){
System.out.println(line);
}
bufferedReader.close();
}
catch (Exception e) {
// TODO: handle exception
}

四、随机读取

//4.随机读取
try {
System.out.println(
"随机读取文件");
//以只读的方式打开文件
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
//获取文件长度,单位为字节
long len = randomAccessFile.length();
//文件起始位置
int beginIndex = (len>4)?4:0;
//将文件光标定位到文件起始位置
randomAccessFile.seek(beginIndex);
byte[] bytes = new byte[5];
int c;
while((c=randomAccessFile.read(bytes))!=-1){
System.out.println(Arrays.toString(bytes));
}
}
catch (Exception e) {
// TODO: handle exception
}