當前位置:首頁 » 編程語言 » 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提供了多種方法來實現文件編碼的轉換。根據實際需求,可以選擇合適的工具和方法來實現文件編碼的轉換,以滿足不同的應用需求。

熱點內容
觸摸精靈的加密腳本 發布:2025-09-01 14:27:08 瀏覽:258
c語言c學那個好 發布:2025-09-01 14:06:22 瀏覽:599
手提箱怎麼設密碼 發布:2025-09-01 13:53:30 瀏覽:142
phpcmsv9附件上傳 發布:2025-09-01 13:41:46 瀏覽:62
軟體開發php 發布:2025-09-01 13:41:45 瀏覽:216
考試網站源碼 發布:2025-09-01 13:39:33 瀏覽:266
機房網路伺服器虛擬搭建 發布:2025-09-01 13:33:40 瀏覽:799
緩存完 發布:2025-09-01 13:23:19 瀏覽:510
資料庫數據分級 發布:2025-09-01 13:21:56 瀏覽:980
hadoop存儲小文件格式 發布:2025-09-01 13:00:58 瀏覽:111