更新時間:2022-12-12 16:13:56 來源:動力節(jié)點 瀏覽4941次
Java寫入數(shù)據(jù)進txt文件,需求:多條數(shù)據(jù)追加進文件,且需要處理中文編碼問題。
以下代碼只能處理向文件添加數(shù)據(jù)的功能,但是會覆蓋掉之前的數(shù)據(jù)
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();
}
}
以上就是動力節(jié)點小編介紹的"基礎(chǔ)入門學(xué)習(xí):Java把內(nèi)容寫入txt文件",希望對大家有幫助,如有疑問,請在線咨詢,有專業(yè)老師隨時為您務(wù)。
相關(guān)閱讀