2017-12-21 6 views
-1
ZipFile zipFile = null; 
InputStreamReader fileReader = null; 
CSVParser csvReportParser = null; 
List<CSVRecord> reportRecord = null; 

try 
{ 
    zipFile = new ZipFile(reportPath); 
    Enumeration<? extends ZipEntry> entries = zipFile.entries(); 
    /** Assuming there is only one file in zip */ 
    ZipEntry entry = entries.nextElement(); 
    InputStream stream = zipFile.getInputStream(entry); 
    fileReader = new InputStreamReader(stream, CHARSET_NAME); 
    csvReportParser = new CSVParser(fileReader, csvFormat); 
    reportRecord = csvReportParser.getRecords(); 
} 
catch (FileNotFoundException e) 
{ 
    LOG.error("File not found at path" + reportPath, e); 
    throw new ClientConsoleException(e); 
} 
catch (IOException e) 
{ 
    LOG.error("Error in reading file at path" + reportPath, e); 
    throw new ClientConsoleException(e); 
} 
finally 
{ 
    IOUtils.closeQuietly(csvReportParser); 
    IOUtils.closeQuietly(fileReader); 
    try 
    { 
    if (zipFile != null) 
     zipFile.close(); 
    } 
    catch (final IOException e) 
    { 
    LOG.error("Cannot close zip file" + reportPath, e); 
    } 
} 

return reportRecord; 

私は上記のコードでリソースを試してみたいです。ここではすでにブロックを試していますが、ここでは3つのクラスだけがtry with resourceブロックに書き込まれます。 リソースを試して、コードの上に正しい方法で記述するのを手伝ってもらえますか?下図のようにカッコでそれをラップし、試し-とリソースの文にリソースを置くためにtryブロック内のコードのリソース呼び出しを試行してください

+2

あなたは「唯一の3つのクラスがブロックに書き込むことができる」とはどういう意味ですか?何が起こるか、望ましくないこと、そして達成したいことを正確に説明してください。 –

+0

Closeableを実装するリソース(クラス)は、try with resources内にのみ記述できます。このメソッドでは、tryリソースリストに3つのクラスを記述できます。しかし、私は以下のメソッドやリソースをtryリソースリストに変換するのに成功しました。 – Sushanth

+0

まだhttps://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.htmlを読んでいますか? – VGR

答えて

0

:あるとして

public static List<CSVRecord> example() { 
    CSVParser csvReportParser = null; 
    List<CSVRecord> reportRecord = new ArrayList<>(); 
    String reportPath = "bla"; 

    try (ZipFile zipFile = new ZipFile(reportPath)) { 
     Enumeration<? extends ZipEntry> entries = zipFile.entries(); 
     ZipEntry entry = entries.nextElement(); 
     InputStream stream = zipFile.getInputStream(entry); 

     try (InputStreamReader fileReader = new InputStreamReader(stream, CHARSET_NAME)) { 
      // do stuff 
     } 
    } catch (IOException e) { 
     // log 
    } finally { 
     IOUtils.closeQuietly(csvReportParser); 
    } 

    return reportRecord; 
} 

を私はCSVParserがあるかわからないので、私はそれを残しました。それはClosableインタフェースを実装する場合は、CSVParserも同様のtry-と資源文の中に含めることができる。

try (ZipFile zipFile = new ZipFile(reportPath); 
    CSVParser csvReportParser = new CSVParser(fileReader, csvFormat)) { 
    ... 
} 
関連する問題