您好,登錄后才能下訂單哦!
字節輸入輸出流:
- 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();
- }
- }
- }
- }
- }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。