0

で存在するファイルを書く方法はFileOutputStream?このプログラムを2回実行すると、2回目oosfosnullになります

 public class ReadFile {
    static FileOutputStream fos = null;
    static ObjectOutputStream oos = null;
    public static void main(String[] args) throws IOException, ClassNotFoundException {

        File f = new File("file.tmp");
        if (f.exists()) {
            //How to retreive an old oos to can write on old file ?
            oos.writeObject("12345");
            oos.writeObject("Today");
        }
        else
        {
            fos = new FileOutputStream("file.tmp");
            oos = new ObjectOutputStream(fos);
        }
        oos.close();
    }
 }
4

5 に答える 5

2
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f,true));

ファイルに追加したい場合

于 2012-11-05T13:01:48.227 に答える
1

ファイルを上書きしたくない場合は、FileまたはFileOutputStreamコンストラクターにtrue引数を追加します

new FileOutputStream( new File("Filename.txt"), true );

Parameters:
name - the system-dependent file name
append - if true, then bytes will be written to the end of the file rather than the beginning 
于 2012-11-05T13:01:05.140 に答える
1

プレーンテキストを作成する場合は、のFileWriter代わりにを使用してみてください。FileOutputStream

    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("outfilename", true)));
    out.println("the text");

2番目のパラメータ(true)は、ファイルに追加するように指示します。

于 2012-11-05T13:01:59.663 に答える
0
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f, true));

あなたのコードにはObjectOutputStream oos = null;、がoosありnullます。初期化する必要があります。このような:

public class ReadFile {
    static FileOutputStream fos = null;
    static ObjectOutputStream oos = null;
    public static void main(String[] args) throws IOException, ClassNotFoundException {

        File f = new File("file.tmp");
        oos = new ObjectOutputStream(new FileOutputStream(f, true));
        if (f.exists()) {
            //How to retreive an old oos to can write on old file ?
            oos.writeObject("12345");
            oos.writeObject("Today");
        }
        else
        {
            fos = new FileOutputStream(f, true);
            oos = new ObjectOutputStream(fos);
        }
        oos.close();
    }
 }
于 2012-11-05T13:00:44.683 に答える
0

FileOutputStream2番目の引数をに設定してnewを作成するだけですtrue

FileOutputStream d = new FileOutputStream(file, append);
于 2012-11-05T13:02:43.623 に答える