无法写入文件

时间:2015-07-15 12:43:47

标签: java

我正在读取一个.gzip文件内容并在阅读完该内容后进行一些计算。现在的问题是我无法将内容写入文件。我的代码如下......

public static void  readAndWrite(File fileName, File outputFilePaht) throws Exception {

        GZIPInputStream gzip = null;
        BufferedReader br = null;
        String line = "";
        FileReader fileReader = new FileReader(fileName);
        BufferedReader bufferedReader = null;
        if(!outputFilePaht.exists()){
            outputFilePaht.createNewFile();
        }
        FileWriter fileWriter = new FileWriter(outputFilePaht,true);
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
        gzip = new GZIPInputStream(new FileInputStream(fileName));
        bufferedReader = new BufferedReader(new InputStreamReader(gzip));
        try{

            while((line = bufferedReader.readLine())!=null){
                if(line.contains("Someservername")){
                    bufferedWriter.write(line);
                    System.out.println(line);
                }
            }
            fileReader.close();
        }catch(Exception e){
            System.out.println(e);
        }
        finally{
            if(fileWriter!=null)
                fileWriter.close();
        }

    }

我做错了吗?请在这里建议我。我无法向文件写任何内容。

提前致谢

1 个答案:

答案 0 :(得分:0)

尝试以下(未经测试):

public static void readAndWrite(Path srcFilePath, Path outputFilePath) throws Exception {

    try (BufferedReader bufferedReader = new BufferedReader(
            new InputStreamReader(new GZIPInputStream(Files.newInputStream(srcFilePath))));
         BufferedWriter bufferedWriter = Files.newBufferedWriter(outputFilePath, 
                 StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.APPEND)) {
        String line;

        while ((line = bufferedReader.readLine()) != null) {
            if (line.contains("Someservername")) {
                bufferedWriter.write(line);
                System.out.println(line);
            }
        }
    } catch (Exception e) {
        System.err.println(e);
    }
}

try-with-resources语句将为您正确关闭流。