Java讀寫文本文件,可以是txt,html等
//讀取文件 (文件路徑,文件編碼)
public String Read(String filepath,String coding) throws Exception{
String templateContent = "";
FileInputStream fileinputstream = new FileInputStream(filepath);// 讀取模板文件
int lenght = fileinputstream.available();
byte bytes[] = new byte[lenght];
fileinputstream.read(bytes);
fileinputstream.close();
//System.out.println(bytes);
templateContent = new String(bytes, coding); ;
//System.out.print(templateContent);
return templateContent;
}
//生成(生成文件路徑,寫入的String,文件編碼)
public void Save(String filepath,String stream,String coding) throws Exception{
File file = new File(filepath);
FileOutputStream fos = new FileOutputStream(file);
Writer out = new OutputStreamWriter(fos, coding);
out.write(stream);
out.flush();
out.close();
fos.close();
fos.flush();
調用如:對象.Read(path+"//test.txt","GBK"); 可以是GBK UTF-8等