Java讀寫文件:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class ReadAndWrite {
public static void main(String[] args)
{
ReadAndWrite.WriteFile("F://2.txt",ReadAndWrite.Read("F://1.txt")); 把1的內容讀出來,寫到2去
}
// 讀文件
public static StringBuffer Read(String filePath)
{
StringBuffer sb=new StringBuffer();
String str=null;
try
{
BufferedReader br=new BufferedReader
(new InputStreamReader(new FileInputStream(filePath)));
while((str=br.readLine())!=null)
{
sb.append(str);
}
br.close();
}
catch(Exception e)
{
e.printStackTrace();
}
return sb;
}
// 寫文件
public static void WriteFile(String filePath,StringBuffer text)
{
try
{
BufferedWriter rw=new BufferedWriter
(new OutputStreamWriter(new FileOutputStream(filePath)));
rw.write(new String(text));
rw.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}