簡體   English   中英

如何將文本附加到 Java 中的現有文件?

[英]How to append text to an existing file in Java?

我需要將文本重復附加到 Java 中的現有文件中。 我怎么做?

你這樣做是為了記錄目的嗎? 如果是這樣,那么有幾個庫 其中最流行的兩個是Log4jLogback

Java 7+

對於一次性任務, Files 類使這很容易:

try {
    Files.write(Paths.get("myfile.txt"), "the text".getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
    //exception handling left as an exercise for the reader
}

小心:如果文件不存在,上述方法將拋出NoSuchFileException 它也不會自動附加換行符(在附加到文本文件時通常需要)。 另一種方法是同時傳遞CREATEAPPEND選項,如果文件不存在,它將首先創建文件:

private void write(final String s) throws IOException {
    Files.writeString(
        Path.of(System.getProperty("java.io.tmpdir"), "filename.txt"),
        s + System.lineSeparator(),
        CREATE, APPEND
    );
}

但是,如果您將多次寫入同一個文件,則上述代碼段必須多次打開和關閉磁盤上的文件,這是一個緩慢的操作。 在這種情況下, BufferedWriter更快:

try(FileWriter fw = new FileWriter("myfile.txt", true);
    BufferedWriter bw = new BufferedWriter(fw);
    PrintWriter out = new PrintWriter(bw))
{
    out.println("the text");
    //more code
    out.println("more text");
    //more code
} catch (IOException e) {
    //exception handling left as an exercise for the reader
}

筆記:

  • FileWriter構造函數的第二個參數將告訴它追加到文件,而不是寫入新文件。 (如果文件不存在,將被創建。)
  • 對於昂貴的寫入器(例如FileWriter ),建議使用BufferedWriter
  • 使用PrintWriter可以讓您訪問您可能從System.out習慣的println語法。
  • 但是BufferedWriterPrintWriter包裝器並不是絕對必要的。

較早的 Java

try {
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true)));
    out.println("the text");
    out.close();
} catch (IOException e) {
    //exception handling left as an exercise for the reader
}

異常處理

如果您需要對舊 Java 進行強大的異常處理,它會變得非常冗長:

FileWriter fw = null;
BufferedWriter bw = null;
PrintWriter out = null;
try {
    fw = new FileWriter("myfile.txt", true);
    bw = new BufferedWriter(fw);
    out = new PrintWriter(bw);
    out.println("the text");
    out.close();
} catch (IOException e) {
    //exception handling left as an exercise for the reader
}
finally {
    try {
        if(out != null)
            out.close();
    } catch (IOException e) {
        //exception handling left as an exercise for the reader
    }
    try {
        if(bw != null)
            bw.close();
    } catch (IOException e) {
        //exception handling left as an exercise for the reader
    }
    try {
        if(fw != null)
            fw.close();
    } catch (IOException e) {
        //exception handling left as an exercise for the reader
    }
}

您可以使用將標志設置為truefileWriter進行追加。

try
{
    String filename= "MyFile.txt";
    FileWriter fw = new FileWriter(filename,true); //the true will append the new data
    fw.write("add a line\n");//appends the string to the file
    fw.close();
}
catch(IOException ioe)
{
    System.err.println("IOException: " + ioe.getMessage());
}

這里的所有 try/catch 塊的答案不應該都包含在 finally 塊中的 .close() 片段嗎?

標記答案的示例:

PrintWriter out = null;
try {
    out = new PrintWriter(new BufferedWriter(new FileWriter("writePath", true)));
    out.println("the text");
} catch (IOException e) {
    System.err.println(e);
} finally {
    if (out != null) {
        out.close();
    }
} 

此外,從 Java 7 開始,您可以使用try-with-resources 語句 關閉聲明的資源不需要 finally 塊,因為它是自動處理的,而且也不那么冗長:

try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("writePath", true)))) {
    out.println("the text");
} catch (IOException e) {
    System.err.println(e);
}

使用 Apache Commons 2.1:

import org.apache.logging.log4j.core.util.FileUtils;

FileUtils.writeStringToFile(file, "String to append", true);

稍微擴展Kip 的答案,這是一個簡單的 Java 7+ 方法,用於將新行附加到文件,如果它不存在則創建它

try {
    final Path path = Paths.get("path/to/filename.txt");
    Files.write(path, Arrays.asList("New line to append"), StandardCharsets.UTF_8,
        Files.exists(path) ? StandardOpenOption.APPEND : StandardOpenOption.CREATE);
} catch (final IOException ioe) {
    // Add your own exception handling...
}

進一步說明:

  1. 上面使用了將文本寫入文件的Files.write重載(即類似於println命令)。 要將文本寫入末尾(即類似於print命令),可以使用替代的Files.write重載,傳入一個字節數組(例如"mytext".getBytes(StandardCharsets.UTF_8) )。

  2. CREATE選項僅在指定目錄已存在時才有效 - 如果不存在,則拋出NoSuchFileException 如果需要,可以在設置path后添加以下代碼來創建目錄結構:

     Path pathParent = path.getParent(); if (!Files.exists(pathParent)) { Files.createDirectories(pathParent); }

確保流在所有情況下都正確關閉。

令人擔憂的是,這些答案中有多少會在出現錯誤時使文件句柄保持打開狀態。 答案https://stackoverflow.com/a/15053443/2498188很划算,但這只是因為BufferedWriter()不能拋出。 如果可以,則異常將使FileWriter對象保持打開狀態。

一種更通用的方法,它不關心BufferedWriter()是否可以拋出:

  PrintWriter out = null;
  BufferedWriter bw = null;
  FileWriter fw = null;
  try{
     fw = new FileWriter("outfilename", true);
     bw = new BufferedWriter(fw);
     out = new PrintWriter(bw);
     out.println("the text");
  }
  catch( IOException e ){
     // File writing/opening failed at some stage.
  }
  finally{
     try{
        if( out != null ){
           out.close(); // Will close bw and fw too
        }
        else if( bw != null ){
           bw.close(); // Will close fw too
        }
        else if( fw != null ){
           fw.close();
        }
        else{
           // Oh boy did it fail hard! :3
        }
     }
     catch( IOException e ){
        // Closing the file writers failed for some obscure reason
     }
  }

編輯:

從 Java 7 開始,推薦的方法是使用“try with resources”並讓 JVM 處理它:

  try(    FileWriter fw = new FileWriter("outfilename", true);
          BufferedWriter bw = new BufferedWriter(fw);
          PrintWriter out = new PrintWriter(bw)){
     out.println("the text");
  }  
  catch( IOException e ){
      // File writing/opening failed at some stage.
  }

在 Java-7 中也可以這樣做:

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

//---------------------

Path filePath = Paths.get("someFile.txt");
if (!Files.exists(filePath)) {
    Files.createFile(filePath);
}
Files.write(filePath, "Text to be added".getBytes(), StandardOpenOption.APPEND);

爪哇 7+

以我的拙見,因為我是普通 java 的粉絲,所以我建議它是上述答案的組合。 也許我參加聚會遲到了。 這是代碼:

 String sampleText = "test" +  System.getProperty("line.separator");
 Files.write(Paths.get(filePath), sampleText.getBytes(StandardCharsets.UTF_8), 
 StandardOpenOption.CREATE, StandardOpenOption.APPEND);

如果文件不存在,它會創建它,如果已經存在,它會將sampleText附加到現有文件中。 使用它,可以避免將不必要的庫添加到類路徑中。

這可以在一行代碼中完成。 希望這可以幫助 :)

Files.write(Paths.get(fileName), msg.getBytes(), StandardOpenOption.APPEND);

我只是添加一些小細節:

    new FileWriter("outfilename", true)

2.nd 參數 (true) 是稱為可附加( http://docs.oracle.com/javase/7/docs/api/java/lang/Appendable.html ) 的功能(或接口)。 它負責能夠將一些內容添加到特定文件/流的末尾。 這個接口是從 Java 1.5 開始實現的。 ) with this interface can be used for adding content每個具有此接口的對象(即 )都可以用於添加內容

換句話說,您可以將一些內容添加到您的 gzip 文件中,或者一些 http 進程

使用 java.nio。 文件連同 java.nio.file。 標准開放選項

    PrintWriter out = null;
    BufferedWriter bufWriter;

    try{
        bufWriter =
            Files.newBufferedWriter(
                Paths.get("log.txt"),
                Charset.forName("UTF8"),
                StandardOpenOption.WRITE, 
                StandardOpenOption.APPEND,
                StandardOpenOption.CREATE);
        out = new PrintWriter(bufWriter, true);
    }catch(IOException e){
        //Oh, no! Failed to create PrintWriter
    }

    //After successful creation of PrintWriter
    out.println("Text to be appended");

    //After done writing, remember to close!
    out.close();

這將使用 Files 創建一個BufferedWriter ,它接受StandardOpenOption參數,以及來自結果BufferedWriter的自動刷新PrintWriter 然后可以調用PrintWriterprintln()方法來寫入文件。

此代碼中使用的StandardOpenOption參數:打開文件進行寫入,僅附加到文件,如果文件不存在則創建文件。

Paths.get("path here")可以替換為new File("path here").toPath() 並且Charset.forName("charset name")可以修改以適應所需的Charset

示例,使用番石榴:

File to = new File("C:/test/test.csv");

for (int i = 0; i < 42; i++) {
    CharSequence from = "some string" + i + "\n";
    Files.append(from, to, Charsets.UTF_8);
}

嘗試使用 bufferFileWriter.append,它適用於我。

FileWriter fileWriter;
try {
    fileWriter = new FileWriter(file,true);
    BufferedWriter bufferFileWriter = new BufferedWriter(fileWriter);
    bufferFileWriter.append(obj.toJSONString());
    bufferFileWriter.newLine();
    bufferFileWriter.close();
} catch (IOException ex) {
    Logger.getLogger(JsonTest.class.getName()).log(Level.SEVERE, null, ex);
}
FileOutputStream fos = new FileOutputStream("File_Name", true);
fos.write(data);

true 允許在現有文件中附加數據。 如果我們寫

FileOutputStream fos = new FileOutputStream("File_Name");

它將覆蓋現有文件。 所以選擇第一種方法。

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class Writer {


    public static void main(String args[]){
        doWrite("output.txt","Content to be appended to file");
    }

    public static void doWrite(String filePath,String contentToBeAppended){

       try(
            FileWriter fw = new FileWriter(filePath, true);
            BufferedWriter bw = new BufferedWriter(fw);
            PrintWriter out = new PrintWriter(bw)
          )
          {
            out.println(contentToBeAppended);
          }  
        catch( IOException e ){
        // File writing/opening failed at some stage.
        }

    }

}
    String str;
    String path = "C:/Users/...the path..../iin.txt"; // you can input also..i created this way :P

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    PrintWriter pw = new PrintWriter(new FileWriter(path, true));

    try 
    {
       while(true)
        {
            System.out.println("Enter the text : ");
            str = br.readLine();
            if(str.equalsIgnoreCase("exit"))
                break;
            else
                pw.println(str);
        }
    } 
    catch (Exception e) 
    {
        //oh noes!
    }
    finally
    {
        pw.close();         
    }

這將做你想要的..

你也可以試試這個:

JFileChooser c= new JFileChooser();
c.showOpenDialog(c);
File write_file = c.getSelectedFile();
String Content = "Writing into file"; //what u would like to append to the file



try 
{
    RandomAccessFile raf = new RandomAccessFile(write_file, "rw");
    long length = raf.length();
    //System.out.println(length);
    raf.setLength(length + 1); //+ (integer value) for spacing
    raf.seek(raf.length());
    raf.writeBytes(Content);
    raf.close();
} 
catch (Exception e) {
    //any exception handling method of ur choice
}

最好使用 try-with-resources 然后所有 pre-java 7 最終業務

static void appendStringToFile(Path file, String s) throws IOException  {
    try (BufferedWriter out = Files.newBufferedWriter(file, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
        out.append(s);
        out.newLine();
    }
}

如果我們使用 Java 7 及以上版本並且知道要添加(附加)到文件中的內容,我們可以使用 NIO 包中的newBufferedWriter方法。

public static void main(String[] args) {
    Path FILE_PATH = Paths.get("C:/temp", "temp.txt");
    String text = "\n Welcome to Java 8";

    //Writing to the file temp.txt
    try (BufferedWriter writer = Files.newBufferedWriter(FILE_PATH, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
        writer.write(text);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

有幾點需要注意:

  1. 指定字符集編碼總是一個好習慣,為此我們在StandardCharsets類中有常量。
  2. 該代碼使用try-with-resource語句,其中資源在嘗試后自動關閉。

雖然 OP 沒有詢問,但如果我們想搜索具有某些特定關鍵字的行,例如confidential ,我們可以在 Java 中使用流 API:

//Reading from the file the first line which contains word "confidential"
try {
    Stream<String> lines = Files.lines(FILE_PATH);
    Optional<String> containsJava = lines.filter(l->l.contains("confidential")).findFirst();
    if(containsJava.isPresent()){
        System.out.println(containsJava.get());
    }
} catch (IOException e) {
    e.printStackTrace();
}
FileOutputStream stream = new FileOutputStream(path, true);
try {

    stream.write(

        string.getBytes("UTF-8") // Choose your encoding.

    );

} finally {
    stream.close();
}

然后在上游某處捕獲 IOException。

在項目的任何地方創建一個函數,然后在需要的地方調用該函數。

伙計們,你們必須記住,你們正在調用不是異步調用的活動線程,因為要正確完成它可能需要 5 到 10 頁。 為什么不花更多的時間在你的項目上,忘記寫任何已經寫好的東西。 適當地

    //Adding a static modifier would make this accessible anywhere in your app

    public Logger getLogger()
    {
       return java.util.logging.Logger.getLogger("MyLogFileName");
    }
    //call the method anywhere and append what you want to log 
    //Logger class will take care of putting timestamps for you
    //plus the are ansychronously done so more of the 
    //processing power will go into your application

    //from inside a function body in the same class ...{...

    getLogger().log(Level.INFO,"the text you want to append");

    ...}...
    /*********log file resides in server root log files********/

三行代碼實際上是第二行,因為第三行實際上附加了文本。 :P

圖書館

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

代碼

public void append()
{
    try
    {
        String path = "D:/sample.txt";

        File file = new File(path);

        FileWriter fileWriter = new FileWriter(file,true);

        BufferedWriter bufferFileWriter  = new BufferedWriter(fileWriter);

        fileWriter.append("Sample text in the file to append");

        bufferFileWriter.close();

        System.out.println("User Registration Completed");

    }catch(Exception ex)
    {
        System.out.println(ex);
    }
}

我可能會建議apache commons 項目 這個項目已經提供了一個框架來做你需要的(即靈活的集合過濾)。

以下方法可讓您將文本附加到某個文件:

private void appendToFile(String filePath, String text)
{
    PrintWriter fileWriter = null;

    try
    {
        fileWriter = new PrintWriter(new BufferedWriter(new FileWriter(
                filePath, true)));

        fileWriter.println(text);
    } catch (IOException ioException)
    {
        ioException.printStackTrace();
    } finally
    {
        if (fileWriter != null)
        {
            fileWriter.close();
        }
    }
}

或者使用FileUtils

public static void appendToFile(String filePath, String text) throws IOException
{
    File file = new File(filePath);

    if(!file.exists())
    {
        file.createNewFile();
    }

    String fileContents = FileUtils.readFileToString(file);

    if(file.length() != 0)
    {
        fileContents = fileContents.concat(System.lineSeparator());
    }

    fileContents = fileContents.concat(text);

    FileUtils.writeStringToFile(file, fileContents);
}

它效率不高,但工作正常。 換行符被正確處理,如果一個新文件尚不存在,則會創建一個新文件。

此代碼將滿足您的需求:

   FileWriter fw=new FileWriter("C:\\file.json",true);
   fw.write("ssssss");
   fw.close();

如果您想在特定行中添加一些文本,您可以首先閱讀整個文件,將文本附加到您想要的任何位置,然后覆蓋下面代碼中的所有內容:

public static void addDatatoFile(String data1, String data2){


    String fullPath = "/home/user/dir/file.csv";

    File dir = new File(fullPath);
    List<String> l = new LinkedList<String>();

    try (BufferedReader br = new BufferedReader(new FileReader(dir))) {
        String line;
        int count = 0;

        while ((line = br.readLine()) != null) {
            if(count == 1){
                //add data at the end of second line                    
                line += data1;
            }else if(count == 2){
                //add other data at the end of third line
                line += data2;
            }
            l.add(line);
            count++;
        }
        br.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }       
    createFileFromList(l, dir);
}

public static void createFileFromList(List<String> list, File f){

    PrintWriter writer;
    try {
        writer = new PrintWriter(f, "UTF-8");
        for (String d : list) {
            writer.println(d.toString());
        }
        writer.close();             
    } catch (FileNotFoundException | UnsupportedEncodingException e) {
        e.printStackTrace();
    }
}

我的答案:

JFileChooser chooser= new JFileChooser();
chooser.showOpenDialog(chooser);
File file = chooser.getSelectedFile();
String Content = "What you want to append to file";

try 
{
    RandomAccessFile random = new RandomAccessFile(file, "rw");
    long length = random.length();
    random.setLength(length + 1);
    random.seek(random.length());
    random.writeBytes(Content);
    random.close();
} 
catch (Exception exception) {
    //exception handling
}
/**********************************************************************
 * it will write content to a specified  file
 * 
 * @param keyString
 * @throws IOException
 *********************************************************************/
public static void writeToFile(String keyString,String textFilePAth) throws IOException {
    // For output to file
    File a = new File(textFilePAth);

    if (!a.exists()) {
        a.createNewFile();
    }
    FileWriter fw = new FileWriter(a.getAbsoluteFile(), true);
    BufferedWriter bw = new BufferedWriter(fw);
    bw.append(keyString);
    bw.newLine();
    bw.close();
}// end of writeToFile()

對於 JDK 版本 >= 7

您可以利用這個簡單的方法將給定的內容附加到指定的文件:

void appendToFile(String filePath, String content) {
  try (FileWriter fw = new FileWriter(filePath, true)) {
    fw.write(content + System.lineSeparator());
  } catch (IOException e) { 
    // TODO handle exception
  }
}

我們正在附加模式下構造一個FileWriter對象。

您可以使用以下代碼將內容附加到文件中:

 String fileName="/home/shriram/Desktop/Images/"+"test.txt";
  FileWriter fw=new FileWriter(fileName,true);    
  fw.write("here will be you content to insert or append in file");    
  fw.close(); 
  FileWriter fw1=new FileWriter(fileName,true);    
 fw1.write("another content will be here to be append in the same file");    
 fw1.close(); 

1.7 方法:

void appendToFile(String filePath, String content) throws IOException{

    Path path = Paths.get(filePath);

    try (BufferedWriter writer = 
            Files.newBufferedWriter(path, 
                    StandardOpenOption.APPEND)) {
        writer.newLine();
        writer.append(content);
    }

    /*
    //Alternative:
    try (BufferedWriter bWriter = 
            Files.newBufferedWriter(path, 
                    StandardOpenOption.WRITE, StandardOpenOption.APPEND);
            PrintWriter pWriter = new PrintWriter(bWriter)
            ) {
        pWriter.println();//to have println() style instead of newLine();   
        pWriter.append(content);//Also, bWriter.append(content);
    }*/
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM