在文件Android中读取时非常奇怪的NullPointerException

时间:2014-03-19 14:02:14

标签: java android file-io simple-framework

以下是代码:

Thread clientThread = new Thread() {
            @Override
            public void run() {
                try {
                    client = new Client();
                    quest = client.readFile();
                    Log.v("Client string", quest);

                    //File file = new File(myContext.getFilesDir(), "questionnaire.xml");
                    //BufferedWriter bw = new BufferedWriter(new FileWriter(file));
                    //bw.write(quest);
                    File tempFile = File.createTempFile("questionnaire", ".xml");
                    FileOutputStream fout = new FileOutputStream(tempFile);
                    PrintStream out = new PrintStream(fout);
                    out.println(quest);//InputStream stream = new ByteArrayInputStream(quest.getBytes("UTF-8"));
                    //getResources().op
                    try {
                    Serializer serializer = new Persister();
                    responseToQuestionnaire = serializer.read(ResponseToQuestionnaire.class, tempFile);
                    }
                    catch(Exception e) {}
                    Log.v("Let's seeeeee",responseToQuestionnaire.getQuestionnaireTemplate().toString());

                } catch (Exception e1) {
                    e1.printStackTrace();
                }
//              try {
//                  OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
//                          openFileOutput(currentQuestionnaire.getName(),
//                                  Context.MODE_PRIVATE));
//                  outputStreamWriter.write(client.readFile());
//                  outputStreamWriter.close();
//              } catch (IOException e) {
//                  Log.e("Exception", "File write failed: " + e.toString());
//              }
            }
        };
        clientThread.start();

代码抛出Null指针异常,即使任务是一个完整长度的字符串,在日志中打印完全正常。我尝试了多种保存文件的方法,但SimpleXML没有串行化字符串...只有XML文件。

1 个答案:

答案 0 :(得分:0)

缓冲流不一定要写入数据。尝试在调用read()方法之前关闭输出流。