java_25 FileReader类和FileWriter类

1.FileWriter

  1.1FileWriter 用于写入字符流。要写入原始字节流,请考虑使用 FileOutputStream

public class Demo {
public static void main(String[] args) throws IOException{
FileWriter fileWriter = new FileWriter("d:\\aaa.txt");
//添加字符
fileWriter.write(100);
fileWriter.write(101);
//添加字符数组
char[] c = {'a','b','c','d'};
fileWriter.write(c);
fileWriter.write(c,1,2);
//添加字符串
fileWriter.write("hello world");
fileWriter.flush();
fileWriter.close();
}
}

2.FileReader

  1.1用来读取字符文件的便捷类。FileReader 用于读取字符流。要读取原始字节流,请考虑使用 FileInputStream

  //flush  和close区别
       // flush用来刷新缓冲区的  只有字符流才需要刷新

  字节读取

public class Demo {
public static void main(String[] args) throws IOException{
FileReader fileReader = new FileReader("d:\\aaa.txt");
int len = 0;
while((len=fileReader.read())!=-1) {
System.out.print((char)len);
}
fileReader.close();
}
}

  字符数组读取

public class Demo {
public static void main(String[] args) throws IOException{
FileReader fileReader = new FileReader("d:\\aaa.txt");
char[] b = new char[1024];
int len = 0;
while((len = fileReader.read(b))!=-1) {
System.out.println(new String(b,0,len));
}
fileReader.close();
}
}

3.传输数据

  

public class Demo {
public static void main(String[] args){
FileReader fileReader = null;
FileWriter fileWriter = null;
try {
fileReader = new FileReader("d:\\aaa.txt");
fileWriter = new FileWriter("d:\\bbb/txt");
char[] ch = new char[1024];
int len = 0;
while((len=fileReader.read(ch))!=-1) {
fileWriter.write(ch,0,len);
fileWriter.flush();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(fileWriter!=null) {
try {
fileWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(fileReader!=null) {
try {
fileReader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
上一篇:PAT1115:Counting Nodes in a BST


下一篇:Windows平台监听服务无法启动报报TNS-12560 TNS-00530案例