天天看點

java中怎樣向檔案裡輸入字元串_Java如何向檔案中附加(寫入)字元串?

在java程式設計中,如何向現有檔案中附加(寫入)一個字元串?

此示例顯示如何使用filewriter()方法在現有檔案中附加字元串。

package com.yiibai;

import java.io.*;

public class AppendString2File {

public static void main(String[] args) throws Exception {

String filename = "write-filename.txt";

try {

BufferedWriter out = new BufferedWriter(new FileWriter(filename));

out.write("This is the first String1\n");

out.close();

out = new BufferedWriter(new FileWriter(filename, true));

out.write("This is the second String2\n");

out.close();

BufferedReader in = new BufferedReader(new FileReader(filename));

String str;

// 輸出檔案内容

while ((str = in.readLine()) != null) {

System.out.println(str);

}

in.close();

} catch (IOException e) {

System.out.println("exception occoured" + e);

}

}

}

執行上述示例代碼,将産生以下結果 -

This is the first String1

This is the second String2

示例-2

以下是在java中向檔案中附加(寫入)字元串的另一個示例。

package com.yiibai;

import java.io.File;

import java.io.FileWriter;

import java.io.BufferedWriter;

import java.io.IOException;

public class AppendString2File2 {

public static void main( String[] args ) {

try {

String data = " yiibai.com is one of the best website in the world";

File f1 = new File("F:/worksp/javaexamples/java_files/write-filename2.txt");

if(!f1.exists()) {

f1.createNewFile();

}

FileWriter fileWritter = new FileWriter(f1.getName(),true);

BufferedWriter bw = new BufferedWriter(fileWritter);

bw.write(data);

bw.close();

System.out.println("Done");

} catch(IOException e){

e.printStackTrace();

}

}

}

執行上述示例代碼,将産生以下結果 -

Done

¥ 我要打賞

糾錯/補充

收藏

加QQ群啦,易百教程官方技術學習群

注意:建議每個人選自己的技術方向加群,同一個QQ最多限加 3 個群。