几种文件读入的方式并比较:
所需包是:
import java.io.*;
1)只能读入字符,不能读入汉字:
采用文件输入流
读取文件的写法:
FileInputStream in=new FileInputStream(new File(“test.txt”));
while(in.available()>0)
{
System.out.print(in.read());//输出
ASCII码
System.out.print((char)in.read());//输出字符
}
in.close();//关闭文件
2)按行读取,可读取汉字
读取文件的方法:
String s;
BufferedReader in=new BufferedReader(new FileReader(“test.txt”));
s=in.readLine();//读取一行
System.out.println(s);//输出这一行
in.close();//关闭文件
3)全文一次读取
(读取的结果放在字符数组中,并不是可以直接用来输出的String类型)
读取文件的写法:
File file=new File(“test.txt”);
int fileSize=(int)file.length(); //读出文件的总长度,并不是字符的总长度
int charsReaded=0;//用来表示所有文字的总长度,一般会比
fileSize小
FileReader in=new FileReader(file);
char[] data=new char[fileSize];//建立一个字符数组
while(in.ready())//判断结束
{
charsReaded+=in.read(data,charsReaded,fileSize-charsReaded);
}
//如果把上一句写为:
in.read(data,0,fileSize);则会把文件中最后的空格也读入data中,
String s1=new String(data,0,charsReaded);//把纯字符数组转变为
String类型
System.out.println(s1);//将其输出
in.close();//关闭文件
4)采用数据输入流,只能读取字符,不能读取汉字
读取文件的写法:
DataInputStream in;
in = new DataInputStream(
new BufferInputStream(
new FileInputStream(“test.txt”)));
String s;
for(;;)
{
s=in.readLine();//读取一行
if(s==null)//作判断
,什么时间结束
break;
System.out.println(s);
}
5)采用标准输入流,可读取汉字,重定向标准输入
读取文件的方法:
BufferedInputStream in=
new BufferedInputStream(
new FileInputStream(
“test.txt”));
//重定向标准输入
System.setIn(in);
BufferedReader reader=
new BufferedReader(
new InputStreamReader(System.in));
String str;
While((str=reader.readLine())!=null)
System.out.println(str);
in.close();
几种文件存盘方式:
1)采用
PrintStream,可对String对象类型数据直接存盘,可处理中文
程序写法:
PrintStream outStream;
outStream=new PrintStream(
new FileOutputStream(“out.txt”));//建立文件
out.txt
//若需存盘的内容放在一个
String对象s中,则:
outStream.println(s);
2)采用
FileOutStream,存盘数据类型是:byte[],可处理中文
程序写法:
FileOutputStream out=new FileOutStream(
new File(“test.txt”));
byte[] b=new byte[1024];
String str= “dkajskdfjal贵州大学计理所
”;
b=str.getBytes();//进行类型转化
out.write(b);//写入磁盘文件中
3)采用重定向标准输出
程序写法:
PrintStream out=
new PrintStream(
new BufferOutputStream(
new FileOutputStream(
“out.txt”)));
//重定向标准输出
System.setOut(out);
//若读取的数据已经存在
String对象str中
System.out.println(str);
//利用正常的输出语句而输出文件
out.txt中
out.close();