从数据流向上可分为输入流和输出流
从数据内容上可分为字节流和字符流
输入输出字符流的父类是Reader和Writer类,
Writer中包含五种写入的方法,
write(char[] cbuf)
write(char[] cbuf, int off, int len)
write(int c)
write(String str)
write(String str, int off, int len)
package execisetest;
import java.io.*;
public class FileWriterDemo {
public static void main(String[] args) {
FileWriter file=null;
try{
file=new FileWriter("d:\\Demo.txt",false);
file.write("okpkpk");
}catch(IOException e){
System.out.println("catch"+e.toString());
}
finally{
try {
if(file!=null)
file.close();
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
}
读取的字符方法包含
read()
read(char[] cbuf)
read(char[] cbuf, int off, int len)
read(CharBuffer target)
返回值均为int代表读入的字符数,代码示例
package execisetest;
import java.io.*;
public class FileReaderDemo {
public static void main(String [] args)throws IOException {
FileReader file=new FileReader("d:\\FileWriterDemo.java");
int num=0;
char [] buf=new char[1024];
while((num=file.read(buf))!=-1)
{
System.out.println(new String(buf,0,num));
}
file.close();
}
}
一个拷贝文件的方法
package execisetest;
import java.io.*;
public class FileCopy {
public static void main(String[] args)
{
copyfile();
}
public static void copyfile()
{
FileWriter fw=null;
FileReader fr=null;
try{
fw=new FileWriter("d:\\dd.txt");
fr=new FileReader("e:\\dd.txt");
char [] buf=new char[1024];
int num=0;
while((num=fr.read(buf))!=-1)
{
System.out.println(1);
fw.write(buf,0,num);
}
}catch(IOException e){
System.out.println(e.toString());
}
finally {
try{
fr.close();
fw.close();
}
catch(IOException e){
System.out.println(e.toString());
}
}
}
}