2016-04-02 6 views
2

このメソッドがOutputStreamをクローズしてメモリリークが発生しないようにするにはどうすればよいですか?このメソッドが出力ストリームを閉じていることを確認するにはどうすればよいですか?

public static void store(Properties properties, Class script) throws IOException { 
    ScriptManifest scriptManifest = (ScriptManifest) script.getAnnotation(ScriptManifest.class); 
    if (scriptManifest != null) { 
     String name = scriptManifest.name(); 
     FileOutputStream outputStream = new FileOutputStream(Constants.SCRIPT_PROPERTIES_DIR + File.separator + name + ".properties"); 
     properties.store(outputStream, ""); 
     outputStream.close(); 
    } else { 
     throw new RuntimeException("Script " + script.getName() + " does not have a ScriptManifest."); 
    } 
} 
+0

@OliverCharlesworth申し訳ありませんが、私はOutputStreamをメンター。 – user2997204

+0

https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html –

答えて

2

を使用することができます。例:

public static void store(Properties properties, Class script) throws IOException { 
    ScriptManifest scriptManifest = (ScriptManifest) script.getAnnotation(ScriptManifest.class); 
    if (scriptManifest != null) { 
     String name = scriptManifest.name(); 
     try (FileOutputStream outputStream = new FileOutputStream(Constants.SCRIPT_PROPERTIES_DIR + File.separator + name + ".properties")) { 
      properties.store(outputStream, ""); 
     } 
    } else { 
     throw new RuntimeException("Script " + script.getName() + " does not have a ScriptManifest."); 
    } 
} 

かのようにブロックし、最終的に試してみてください。

public static void store(Properties properties, Class script) throws IOException { 
    ScriptManifest scriptManifest = (ScriptManifest) script.getAnnotation(ScriptManifest.class); 
    if (scriptManifest != null) { 
     String name = scriptManifest.name(); 
     FileOutputStream outputStream = null; 
     try { 
      outputStream = new FileOutputStream(Constants.SCRIPT_PROPERTIES_DIR + File.separator + name + ".properties"); 
      properties.store(outputStream, ""); 
     } finally { 
      if (outputStream != null) outputStream.close(); 
     } 
    } else { 
     throw new RuntimeException("Script " + script.getName() + " does not have a ScriptManifest."); 
    } 
} 
1

2つのアプローチがあります。 Javaのそれ以降のバージョンで

FileOutputStream outputStream = null; 
try { 
    outputStream = new FileOutputStream(...) 
    ... 
} 
catch (IOException e) { 
    throw new RuntimeException(...) 
} 
finally { 
    // or use the Apache Commons IOUtils.closeQuietly(outputStream); 
    // and then only need the one line 
    if (outputStream != null) { 
     try { 
     outputStream.close(); 
     } 
     catch (Exception ignore) { } 
    } 
} 

、あなたはあなたがtry-with-resourcesを使用することができますのtry-と資源

try (FileOutputStream fos = new FileOutputStream("f:/tmp/stops.csv")) { 
} 
catch (IOException e) { 
} 
+0

スローを削除せずにこれを行うことは可能ですか.... ...? – user2997204

+0

@ user2997204のいずれの方法でも、必要に応じて(IOExceptionから)別の例外をスローすることができます。最初の例で説明するために編集しました。 – KevinO

関連する問題