这2中方法都行吗?
package file;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Speech {
public static void main(String[] args) {
try {
FileInputStream a=new FileInputStream("speech.txt");
File b=new File("speech.txt");
int n=0;
int count=0;
System.out.print("文本内容:");
while((n=a.read())!=-1) {
System.out.print((char)n);
count++;
}
System.out.println();
System.out.println("统计结果:"+b.getName()+"文件中共有"+count+"个字节。");
a.close();
} catch (FileNotFoundException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}package file;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Speech2 {
public static void main(String[] args) {
try {
FileInputStream a=new FileInputStream("speech.txt");
File q=new File("speech.txt");
byte[]b=new byte[1000];
int count=a.read(b);
System.out.print("文本内容:");
while((a.read(b))!=-1) {
System.out.println(new String(b));
count++;
}
System.out.println("统计结果:"+q.getName()+"文件中共有"+count+"个字节。");
a.close();
} catch (FileNotFoundException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}2
收起
正在回答
2回答
同学你好,两种方式都是可以的,但是在第二种方法中,返回实际读取到字节数组中的字节,因为初始化char类型的数组为1000个,如果读取文件中的字节数小于1000,则会使用char类型的初始化方框补充,进行读取。例如如下输出结果:

另外,在第二段代码中,应该将count值初始化为0,否则将不会输出内容,因为如果初始化为读取的字节数,进行count++将没有内容读出,具体见如下修改:

综上所述,建议使用第一种方式读取文件哦~
如果我的回答解决了你的疑惑,请采纳!祝学习愉快!
1. Java 零基础入门
- 参与学习 人
- 提交作业 3802 份
- 解答问题 11489 个
本阶段带你迈入Java世界,学习Java必备基础知识,基础语法、面向对象思想以及常用工具类的使用。
了解课程

恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星