字节输入输出流:
- FileInputStream fis = new FileInputStream(filePath);
- FileOutputStream fos = new FileOutputStream(savePath);
- byte[] buffer = new byte[1024];
- int length = 0;
- while (-1 != (length = fis.read(buffer)))
- {
- fos.write(buffer);
- /**
- * 等价于下面的写法:
- * String str = new String(buffer, 0, length);
- * fos.write(str.getBytes());
- */
- }
字符输入输出流:
- FileReader fr = new FileReader(fileName);
- char[] buffer = new char[1024];//使用字符数组
- int length = 0;
- while (-1 != (length = fr.read(buffer)))
- {
- for (int i = 0; i < length; i++)
- {
- System.out.print(buffer[i]);
- }
- }
- FileWriter fw = new FileWriter(fileName);
- fw.write("这段字符串按字符写入good");
- fw.flush();//写完清空缓存
转换流、缓冲流:
- FileInputStream fis = new FileInputStream(fileName);
- InputStreamReader isr = new InputStreamReader(fis);
- BufferedReader br = new BufferedReader(isr);
- FileOutputStream fos = new FileOutputStream(saveName);
- OutputStreamWriter osw = new OutputStreamWriter(fos);
- BufferedWriter bw = new BufferedWriter(osw);
- String str = null;
- while (null != (str = br.readLine()))//读取每行直到'\r'或'\t'则为空
- {
- bw.write(str);//write可以写入字符串或者字符
- bw.newLine();//换行
- bw.flush();//清空缓存
- }
文件拷贝方法:练习字节流、字符流、缓冲流、转换流
- public class CopyMethod
- {
- public static void main(String[] args)
- {
- CopyMethod cm = new CopyMethod();
- String scr = "F:/java/tt.txt";
- String dest = "F:/java/xx.txt";
- cm.copyMethod(scr, dest);
- }
- public void copyMethod(String scr,String dest)
- {
- BufferedReader fr = null;
- BufferedWriter bw = null;
- try
- {
- FileInputStream fis = new FileInputStream(scr);//文件输入流
- InputStreamReader isr = new InputStreamReader(fis);//转换流,将字节流转换为字符流
- fr = new BufferedReader(isr);//创建字符缓冲流,每次读取一行字符
- FileOutputStream fos = new FileOutputStream(dest);
- OutputStreamWriter osw = new OutputStreamWriter(fos);
- bw = new BufferedWriter(osw);
- String str = null;//缓冲流读取和写入的都是字符串
- while(null != (str = fr.readLine()))//使用readLine(),读取到\r或\n结束
- {
- bw.write(str);//写入一行字符串
- bw.newLine();//换行
- bw.flush();//清空缓存,使用writer需要flush
- }
- }
- catch (FileNotFoundException e)
- {
- e.printStackTrace();
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
- finally//关闭最外层的流
- {
- if(fr != null)
- {
- try
- {
- fr.close();
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
- }
- if(null != bw)
- {
- try
- {
- bw.close();
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
- }
- }
- }
- }
本文转自 glblong 51CTO博客,原文链接:http://blog.51cto.com/glblong/1191870,如需转载请自行联系原作者