在try catch块中访问和运行代码的问题

时间:2017-05-31 22:29:06

标签: java methods try-catch

由于某种原因,我的程序不会写入该文件,即使我能够使try catch块无错误并运行。我有理由无法访问try块并创建此文件吗?

    public static void main(String[] args) {
    BufferedReader crunchifyBuffer = null;
    try {
        String crunchifyLine;
        crunchifyBuffer = new BufferedReader(new FileReader("/Users/moo/Desktop/test.csv"));
        // How to read file in java line by line?
        while ((crunchifyLine = crunchifyBuffer.readLine()) != null) {
            ArrayList<String> parsedData = new ArrayList<String>();
            parsedData.add(crunchifyCSVtoArrayList(crunchifyLine).get(0));
            parsedData.add(crunchifyCSVtoArrayList(crunchifyLine).get(7));
            parsedData.add(crunchifyCSVtoArrayList(crunchifyLine).get(8));
            System.out.println("\n"+ parsedData + "\n");
            String ID = parsedData.get(0);
            String[] aVPayload = new String[3];
            aVPayload[0] = ID;
            String holder = sdkCall(aVPayload);
            try {
                JSONObject jsonObj = new JSONObject(holder);

                String Lat = jsonObj.getJSONObject("geo").getString("latitude");
                String Long = jsonObj.getJSONObject("geo").getString("longitude");


                try {
                    PrintWriter writer = new PrintWriter("addressValidityReport.txt", "UTF-8");
                    writer.println("ID" + "\t" + "CSV Lat" + "\t" + "CSV Long" + "\t" + "Lat" + "\t" + "Long" + "\t" + "Status" );
                    while ((crunchifyLine = crunchifyBuffer.readLine()) != null) {
                        writer.println((crunchifyCSVtoArrayList(crunchifyLine).get(0)) + "\t" + (crunchifyCSVtoArrayList(crunchifyLine).get(7)) + "\t" + (crunchifyCSVtoArrayList(crunchifyLine).get(8)) + "\t" + Lat + "\t" + Long + "\t" + "FLAGGED" + "\n");
                    }
                    writer.close();
                } catch (IOException e) {
                    System.out.println("ERROR, CHECK FILE PRINTING!");
                }

            } catch (JSONException e) {
                System.out.println("unexpected JSON exception");
            }


        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {

            if (crunchifyBuffer != null) crunchifyBuffer.close();
        } catch (IOException crunchifyException) {
            crunchifyException.printStackTrace();
        }
    }
}

它会运行,但不会创建任何文件。有两个捕获异常导致这个吗?

1 个答案:

答案 0 :(得分:-1)

你需要在close()之前创建一个writer.flush(),强制将数据写入文件

PrintWriter(文件文件,字符串csn) 使用指定的文件和字符集创建一个新的PrintWriter,不带自动行刷新。

检查printl()方法后,我认为它不会刷新()而你可能会丢失你的数据,这就是为什么你最后没有你的文件