更新時間:2022-12-12 16:13:56 來源:動力節點 瀏覽4442次
Java寫入數據進txt文件,需求:多條數據追加進文件,且需要處理中文編碼問題。
以下代碼只能處理向文件添加數據的功能,但是會覆蓋掉之前的數據
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class Write {
public static void main(String[] args) throws IOException {
String word = "hahahahhahahahhah";
FileOutputStream fileOutputStream = null;
File file = new File("F:\test\test.txt");
if(!file.exists()){
file.createNewFile();
}
fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(word.getBytes("gbk"));
fileOutputStream.flush();
fileOutputStream.close();
}
}
正確實例
public class Test{
public static void main(String[] args) throws IOException {
String path = "F:\test\test.txt";
String word = "試試";
BufferedWriter out = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(path,true)));
out.write(word+"
");
out.close();
}
}
以上就是動力節點小編介紹的"基礎入門學習:Java把內容寫入txt文件",希望對大家有幫助,如有疑問,請在線咨詢,有專業老師隨時為您務。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習