java基本io流的操作
阿新 • • 發佈:2019-02-16
1.將控制檯輸入的寫入到txt檔案中
package com.soulant.main;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
/*將控制檯輸入的字元-轉化成位元組-再轉化為字元流寫入檔案
注意事項:
"E:\\JavaTest\\HelloWorld.txt" 而不是 "E:\JavaTest\HelloWorld.txt"
將字串進行轉義
*/
public class TestIo {
public static void main(String[] args)throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String s;
try {
while ((s = in.readLine()).length()!=0) {
System.out.println(s);
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("E:\\JavaTest\\HelloWorld.txt")));
out.println(s);
System.out.println("寫入");
out.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace ();
}
}
}
將txt檔案裡面的內容寫入到另一個檔案中
package com.soulant.main;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
/*
* 將一個txt檔案裡面的內容寫入到另一個txt檔案
*
*/
public class TestFile {
public static void main(String[] args) {
File filein,fileout;
BufferedReader bf = null;
PrintWriter pw = null;
filein = new File("E:\\JavaTest\\filein.txt");
fileout = new File("E:\\JavaTest\\fileout.txt");//如果沒有就會自動建立
try {
bf = new BufferedReader(new FileReader(filein));
pw = new PrintWriter(fileout);//PrintWriter為列印流,也可以使用BufferedWriter.
String line = bf.readLine();
while (line!=null) {
pw.println(line);
line = bf.readLine();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
if (bf!=null) {
bf.close();
bf = null;
}
if (pw!=null) {
pw.close();
pw = null;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}