输入输出流(IO)—文件字符流(FileReader & FileWriter)的基本操作及应用

来源:互联网 发布:网络写手如何投稿 编辑:程序博客网 时间:2024/05/16 14:48

FileReader类是Reader类的子类,称为文件字符输入流。按字符读取文件中的数据。

构造方法:FileReader(String name)

                    FileReader(File file)

读取文件并输出

public void test() throws IOException{
File file = new File("hello.txt");
FileReader in = null;
try{
in = new FileReader(file);
int a = in.read();
String str = new String();
while(a  != -1){
str += (char)a;
a = in.read();
}
System.out.println(str);
}catch(IOException e){
System.out.println(e);
}
}

输出结果为:文件hello.txt中的内容。


FileWriter类是Writer类的子类,称为文件字符输出流。按字符将数据写入文件。

构造方法:FileWriter(String name,boolean append)

                     FileWriter(File file,boolran append)

写入文件并输出

public void test1(){
File file = new File("hello.txt");
char b[] = "Welcome to read my blog!".toCharArray();//字符串中的内容为将写入的内容,需调用toCharArray()函数转换为字符形式
FileWriter out = null;
FileReader in = null;
try{
out = new FileWriter(file);
out.write(b);
out.flush();
in = new FileReader(file);
int n = 0;
while((n = in.read(b, 0, 1))   != -1){
String str = new String(b,0,n);
System.out.println(str);
}
}catch(IOException e){
System.out.println(e);
}
finally{
try{
out.close();
}catch(IOException e){
System.out.println(e);
}
}

}

输出结果为:Welcome to read my blog! //输出内容与写入内容一致。

文件字符流的应用:存在一个已知文件oldfile,用文件字符流进行复制到新的文件newfile,并输出newfile中的内容

public void CopyFile1(String oldFilename,String newFilename){
File nfile = new File(newFilename);
File ofile = new File(oldFilename);
FileWriter out = null;
FileReader in = null;
String str = new String();
try{
in = new FileReader(ofile);
int a = in.read();
while(a  != -1){
str += (char)a;
a = in.read();
}
in.close();
}catch(IOException e){
System.out.println(e);
}
char[] b = str.toCharArray();
try{
out = new FileWriter(nfile);
out.write(b);
out.flush();
out.close();
}catch(IOException e){
System.out.println(e);
}

}

@Test
public void test4() throws IOException{
File oldfile = new File("hello.txt");
File newfile = new File("hel.txt");
FileReader in = null;
CopyFile(oldfile.getName(),newfile.getName());
try{
in = new FileReader(newfile);
int a = in.read();
String str = new String();
while(a  != -1){
str += (char)a;
a = in.read();
}
System.out.println(str);
in.close();
}catch(IOException e){
System.out.println(e);
}
}

输出结果为:hello.txt中的内容,说明复制成功!

0 0
原创粉丝点击