2

私はここでかなり混乱しています。SCJPの準備をしています。flush()メソッドとclose()メソッドの前後にBufferedWriterのメモリ割り当てをチェックするための小さな再帰を作成しました。以下のコードブロックを参照してください。デスクトップファイルをテキストファイルに書き込んだところです。

import java.io.*;

public class Myexception{

    private static String lvl = "";
    static BufferedWriter bw;
    private static File source = new File("C:\\Users\\"+System.getProperty("user.name")+"\\Desktop\\New folder\\myTest.txt");

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

        Runtime rt = Runtime.getRuntime();

        System.out.println("Free memory before recursive: " + rt.freeMemory());

        bw = new BufferedWriter(new FileWriter(source));

        checkFiles(new File("C:\\Users\\"+System.getProperty("user.name")+"\\Desktop"), 0);

        System.out.println("Memory after recursive: " + rt.freeMemory());

        bw.flush();
        bw.close();
        lvl = null;

        System.out.println("Memory after clean up: " + rt.freeMemory());
    }
    static void checkFiles(File file, int level) throws IOException{

        if(!file.exists()){

            System.out.println("File doesnt exist: " + file.getName() + file.getPath());
            return;
        }

        for(String s:file.list()){

            if(new File(file.getPath() + "\\" +  s).isDirectory()){

                bw.newLine();
                bw.write(lvl + "Directory: " + s);

                lvl += " ";

                checkFiles(new File(file.getPath() + "\\" +  s), level+1);

            }else{

                bw.newLine();
                bw.write(lvl + "File: " + s);

            }
        }
    }
}

出力は問題ありませんが、私が理解していなかったことです。flush()とclose()の前のメモリの解放は、flush()とclose()の後でのメモリの解放と同じです。出力を参照してください。

Free memory before recursive: 126150232
Memory after recursive: 104461304
Memory after clean up: 104461304

既存のトピックを確認しましたが、正確な説明が見つかりませんでした。bw.close()の後に、より多くの空きメモリがあることを期待していました。

ありがとうございました

4

2 に答える 2

3

ストリームを閉じてフラッシュすることは、「メモリのクリーンアップ」とは何の関係もありません。BufferedStreamストリームが指しているもの(通常はディスクやネットワークソケットなど)に、a内のデータが確実にフラッシュされるようにします。JavaDocを読んでください。とにかく、これがガベージコレクションに影響を与えることを意味するものではありません。価値のない認定資格にお金を浪費する前に、勉強に戻る必要があります。

于 2011-12-05T13:34:56.967 に答える
1

メモリは、ガベージ コレクターが実行された後にのみ消去されます。それまでは、メモリ消費量に変化は見られません。

于 2011-12-05T14:10:00.603 に答える