public static String readFile(File file, String charset){
//設置默認編碼
if(charset == null){
charset = "UTF-8";
}
if(file.isFile() && file.exists()){
try {
FileInputStream fileInputStream = new FileInputStream(file);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, charset);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer sb = new StringBuffer();
String text = null;
while((text = bufferedReader.readLine()) != null){
sb.append(text);
}
return sb.toString();
} catch (Exception e) {
// TODO: handle exception
}
}
return null;
}
最後此函數將會返回讀取到的內容。當然,也可以在讀取的過程中進行逐行處理,不必要一次性讀出再進行處理。
而且,bufferedReader還有read方法,滿足更多的需要。下去我自己可以試一試,再補充。
/**
* 以FileWriter方式寫入txt文件。
* @param File file:要寫入的文件
* @param String content: 要寫入的內容
* @param String charset:要寫入內容的編碼方式
*/
public static void writeToFile1(){
try {
String content = "測試使用字符串";
File file = new File("./File/test1.txt");
if(file.exists()){
FileWriter fw = new FileWriter(file,false);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close(); fw.close();
System.out.println("test1 done!");
}
} catch (Exception e) {
// TODO: handle exception
}
}
這種方式簡單方便,代碼簡單。順帶一提的是:上述代碼是清空文件重寫,要想追加寫入,則將FileWriter構造函數中第二個參數變為true。
public static void writeToFile2(){
try {
String content = "測試使用字符串";
File file = new File("./File/test2.txt");
//文件不存在時候,主動穿件文件。
if(!file.exists()){
file.createNewFile();
}
FileWriter fw = new FileWriter(file,false);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close(); fw.close();
System.out.println("test2 done!");
} catch (Exception e) {
// TODO: handle exception
}
}
關鍵性的話語在於file.createNewFile();
public static void writeToFile3(){
String content = "測試使用字符串";
FileOutputStream fileOutputStream = null;
File file = new File("./File/test3.txt");
try {
if(file.exists()){
file.createNewFile();
}
fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(content.getBytes());
fileOutputStream.flush();
fileOutputStream.close();
} catch (Exception e) {
// TODO: handle exception
}
System.out.println("test3 done");
}
使用輸出流的方式寫入文件,要將txt文本轉換為bytes寫入。
以後再進行補充學習,暫時就這樣記錄下來。