其實這篇文章其實和imooc一點關係都沒有,但是爲了讓我的博客看起來不那麼亂,我就放一起了。
寫文件
- 利用FileOutputStream寫文件
public static void main(String[] args) throws IOException {
// 創建一個File對象
File file = new File("E:\\test\\test.txt");
// 創建一個file對象的FileOutputStream對象
OutputStream out = new FileOutputStream(file);
// 創建一個FileOutputSteam對象的OutputStreamWriter對象,用於向文件中寫入內容,並設置編碼爲 "UTF-8" 以便於寫入中文字符且保證不會亂碼
OutputStreamWriter writer = new OutputStreamWriter(out,"UTF-8");
// 添加內容到緩衝區中
writer.append("English Test");
// 該方法支持多次調用,"\r\n" 在文件中就是換行符
writer.append("\r\n");
writer.append("中文測試");
// 該方法可以將緩衝區中的內容寫入文件
writer.flush();
// 將緩衝區中的內容寫入文件,並關閉寫入流
writer.close();
// 關閉輸出流(一定要關閉輸出流,不然會影響你在其他地方的使用!)
out.close();
}
- 利用FileWriter寫文件
public static void main(String[] args) throws IOException {
// 創建一個File對象
File file = new File("E:\\test\\test.txt");
// 創建一個file對象的FileWriter對象
FileWriter writer = new FileWriter(file);
// 添加內容到緩衝區中
writer.append("English Test");
// 該方法支持多次調用,"\r\n" 在文件中就是換行符
writer.append("\r\n");
writer.append("中文測試");
// 該方法可以將緩衝區中的內容寫入文件
writer.flush();
// 將緩衝區中的內容寫入文件,並關閉寫入流
writer.close();
}
讀文件
- 利用FileInputStream讀文件
public static void main(String[] args) throws IOException {
// 創建一個File對象
File file = new File("E:\\test\\test.txt");
// 創建一個FileInputSteam對象
InputStream in = new FileInputStream(file);
// 創建一個InputStreamReader對象,編碼要保持一致
InputStreamReader reader = new InputStreamReader(in,"UTF-8");
StringBuffer stringBuffer = new StringBuffer();
// 利用循環來讀取數據
while(reader.ready()){
// 因爲read()方法的返回值是int型,所以需要使用char來強制轉換
stringBuffer.append((char)reader.read());
}
// 在console輸出結果
System.out.println(stringBuffer.toString());
// 關閉reader&in對象,釋放資源佔用
reader.close();
in.close();
}
- 利用FileReader讀文件
public static void main(String[] args) throws IOException {
// 創建一個File對象
File file = new File("E:\\test\\test.txt");
// 創建 FileReader對象
FileReader reader = new FileReader(file);
// 創建一個字符數組用於存儲即將從文件中讀取到的內容
char [] chars = new char[50];
// 將文件中的內容讀取到字符數組中
reader.read(chars);
for(char c : chars)
System.out.print(c);
// 關閉reader,釋放資源
reader.close();
}
備註:FileReader對象需要事前確定長度,而且如果長度大於其內容的長度,會被” “填充,所以不推薦用reader對象吧,如果有可以幫助我解決這個疑問的朋友,歡迎聯繫我,謝謝!