當前位置:首頁 » 編程語言 » java把內容寫入txt文件

java把內容寫入txt文件

發布時間: 2025-09-01 12:00:51

java如何追加寫入txt文件

java中,對文件進行追加內容操作的三種方法!

importjava.io.BufferedWriter;
importjava.io.FileOutputStream;
importjava.io.FileWriter;
importjava.io.IOException;
importjava.io.OutputStreamWriter;
importjava.io.PrintWriter;
importjava.io.RandomAccessFile;
//如果文件存在,則追加內容;如果文件不存在,則創建文件,追加內容的三種方法
{
@SuppressWarnings("static-access")
publicstaticvoidmain(String[]args){
AppendContentToFilea=newAppendContentToFile();
a.method1();
a.method2("E:\dd.txt","222222222222222");
a.method3("E:\dd.txt","33333333333");
}

方法1:

publicvoidmethod1(){
FileWriterfw=null;
try{
//如果文件存在,則追加內容;如果文件不存在,則創建文件
Filef=newFile("E:\dd.txt");
fw=newFileWriter(f,true);
}catch(IOExceptione){
e.printStackTrace();
}
PrintWriterpw=newPrintWriter(fw);
pw.println("追加內容");
pw.flush();
try{
fw.flush();
pw.close();
fw.close();
}catch(IOExceptione){
e.printStackTrace();
}
}

方法2:

publicstaticvoidmethod2(Stringfile,Stringconent){
BufferedWriterout=null;
try{
out=newBufferedWriter(newOutputStreamWriter(
newFileOutputStream(file,true)));
out.write(conent+" ");
}catch(Exceptione){
e.printStackTrace();
}finally{
try{
out.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}

方法3:

publicstaticvoidmethod3(StringfileName,Stringcontent){
try{
//打開一個隨機訪問文件流,按讀寫方式
RandomAccessFilerandomFile=newRandomAccessFile(fileName,"rw");
//文件長度,位元組數
longfileLength=randomFile.length();
//將寫文件指針移到文件尾。
randomFile.seek(fileLength);
randomFile.writeBytes(content+" ");
randomFile.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}

㈡ java 將編碼格式為utf-8的文件內容以 GBK編碼存到txt文檔

在Java中轉換文件編碼格式時,可以使用多種方法。傳統的做法是自己編寫程序,通過讀取文件中的數據並轉換編碼,然後重新寫入。例如,可以將GBK編碼的文本文件轉換為UTF-8編碼。以下是一個具體的示例:

假設需要將一個名為「example.java」的文件從GBK編碼轉換為UTF-8編碼。首先定義兩個路徑,分別指向源文件和目標文件的目錄:

String srcDirPath = "D:\\dev\\workspace\\masdev\\mas\\src";

String utf8DirPath = "D:\\UTF8\\src";

接下來,通過FileUtils.listFiles方法獲取指定目錄下的所有Java文件:

Collection javaGbkFileCol = FileUtils.listFiles(new File(srcDirPath), new String[]{"java"}, true);

然後遍歷這些文件,為每個文件生成目標文件的路徑:

for (File javaGbkFile : javaGbkFileCol) {

String utf8FilePath = utf8DirPath + javaGbkFile.getAbsolutePath().substring(srcDirPath.length());

使用GBK編碼讀取文件內容,並通過UTF-8編碼寫入新文件:

FileUtils.writeLines(new File(utf8FilePath), "UTF-8", FileUtils.readLines(javaGbkFile, "GBK"));

這種方法不僅適用於GBK到UTF-8的轉換,還可以用於其他編碼格式之間的轉換。通過Apache Commons IO庫中的FileUtils類,可以方便地實現文件的讀取和寫入操作。

此外,還可以利用第三方庫,如ICU4J,來處理復雜的字元編碼轉換問題。ICU4J提供了強大的字元處理功能,能夠處理多種語言和編碼標准,包括Unicode和各種區域性的字元集。

總之,Java提供了多種方法來實現文件編碼的轉換。根據實際需求,可以選擇合適的工具和方法來實現文件編碼的轉換,以滿足不同的應用需求。

熱點內容
java返回this 發布:2025-10-20 08:28:16 瀏覽:585
製作腳本網站 發布:2025-10-20 08:17:34 瀏覽:881
python中的init方法 發布:2025-10-20 08:17:33 瀏覽:574
圖案密碼什麼意思 發布:2025-10-20 08:16:56 瀏覽:761
怎麼清理微信視頻緩存 發布:2025-10-20 08:12:37 瀏覽:676
c語言編譯器怎麼看執行過程 發布:2025-10-20 08:00:32 瀏覽:1005
郵箱如何填寫發信伺服器 發布:2025-10-20 07:45:27 瀏覽:249
shell腳本入門案例 發布:2025-10-20 07:44:45 瀏覽:108
怎麼上傳照片瀏覽上傳 發布:2025-10-20 07:44:03 瀏覽:798
python股票數據獲取 發布:2025-10-20 07:39:44 瀏覽:705