0

以下のコードを持っており、一時ファイルを作成してそれを読み、ファイルを削除しています。しかし、削除した後、ファイルも読むことができます。私のコードの間違いを見つけるのを手伝ってください...。

public static void main(String args[]) throws Exception
    {                   
        Calendar mSec = Calendar.getInstance();
        String fileName="hubname_"+"msgname_"+mSec.getTimeInMillis();
        String str ="Hello How are you doing .......";
        System.out.println("fileName :"+fileName);

        File f = File.createTempFile(fileName, ".xml");
        FileWriter fw = new FileWriter(f);
        fw.write(str);
        fw.flush();
        fw.close();

        printFileContent(f);
        f.delete();
        printFileContent(f);

    }
  public static void printFileContent(File f)throws Exception
  {
      BufferedReader reader = new BufferedReader( new FileReader(f));
      String         line = null;
      StringBuilder  stringBuilder = new StringBuilder();
      String         ls = System.getProperty("line.separator");

      while( ( line = reader.readLine() ) != null ) {
          stringBuilder.append( line );
          stringBuilder.append( ls );
      }

      System.out.println("stringBuilder.toString() :"+stringBuilder.toString());
  }

出力:

fileName :hubname_msgname_1358655424194
stringBuilder.toString() :Hello How are you doing .......

stringBuilder.toString() :Hello How are you doing .......
4

2 に答える 2

3

printFileContentでリーダーを閉じる必要があります。File.deleteは、開いているファイルを削除できません(少なくとも、Windowsでは、以下のKeith Randallのコメントを参照してください)。その場合、falseが返されます。削除が成功したかどうかを確認できます

if (!f.delete()) {
    throw new IOException("Cannot delete " + f);
}

次のコメントがJava7のFile.deleteAPIに追加されました

Note that the Files class defines the delete method to throw an IOException when a file cannot be deleted. This is useful for error reporting and to diagnose why a file cannot be deleted.
于 2013-01-20T04:23:52.103 に答える
1
public static void printFileContent(File f)throws Exception
  {
      BufferedReader reader = new BufferedReader( new FileReader(f));
      String         line = null;
      StringBuilder  stringBuilder = new StringBuilder();
      String         ls = System.getProperty("line.separator");

      while( ( line = reader.readLine() ) != null ) {
          stringBuilder.append( line );
          stringBuilder.append( ls );
      }

      System.out.println("stringBuilder.toString() :"+stringBuilder.toString()); 

   if(reader != null){
     reader.close();
    }

  }
于 2013-01-20T04:25:26.213 に答える