9

いくつかのファイルの処理結果を保存している文字列があります。その文字列をプロジェクトの.txtファイルに書き込むにはどうすればよいですか?.txtファイルの目的の名前である別のString変数があります。

4

3 に答える 3

18

これを試して:

//Put this at the top of the file:
import java.io.*;
import java.util.*;

BufferedWriter out = new BufferedWriter(new FileWriter("test.txt"));

//Add this to write a string to a file
//
try {

    out.write("aString\nthis is a\nttest");  //Replace with the string 
                                             //you are trying to write
}
catch (IOException e)
{
    System.out.println("Exception ");

}
finally
{
    out.close();
}
于 2012-04-30T20:47:26.277 に答える
6

好きですか?

FileUtils.writeFile(new File(filename), textToWrite); 

FileUtilsはCommonsIOで利用できます。

于 2012-04-30T20:43:07.513 に答える
5

バイトベースのストリームを使用して作成されたファイルは、バイナリ形式のデータを表します。文字ベースのストリームを使用して作成されたファイルは、データを文字のシーケンスとして表します。テキストファイルはテキストエディタで読み取ることができますが、バイナリファイルはデータを人間が読める形式に変換するプログラムで読み取ることができます。

文字ベースのファイルI/Oをクラス分けFileReaderして実行します。FileWriter

Java 7を使用している場合は、try-with-resourcesメソッドを大幅に短縮するために使用できます。

import java.io.PrintWriter;
public class Main {
    public static void main(String[] args) throws Exception {
        String str = "写字符串到文件"; // Chinese-character string
        try (PrintWriter out = new PrintWriter("output.txt", "UTF-8")) {
            out.write(str);
        }
    }
}

Javaのtry-with-resourcesステートメントを使用して、リソース(不要になったときに閉じる必要があるオブジェクト)を自動的に閉じることができます。java.lang.AutoCloseableリソースクラスはインターフェイスまたはそのサブインターフェイスを実装する必要があることを考慮する必要がありますjava.lang.Closeable

于 2012-04-30T20:55:03.493 に答える