当前位置: 代码迷 >> J2SE >> 为何会抛出NUllPointerException
  详细解决方案

为何会抛出NUllPointerException

热度:6061   发布时间:2013-02-25 21:53:58.0
为什么会抛出NUllPointerException?
本帖最后由 wjpxz 于 2013-01-24 10:44:05 编辑
异常发生在62行,这是异常代码:
Exception in thread "main" java.lang.NullPointerException
at java.io.Writer.write(Unknown Source)
at test.util.ComposeMessage.composeMessage(ComposeMessage.java:62)
at test.util.ComposeMessage.main(ComposeMessage.java:118),
虽然能够正常把字符串数组result的内容写入到文件中,但是eclipse中这里还是有错误,有没有大神知道为啥啊?谢谢各位了!

package test.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class ComposeMessage {
public static void composeMessage(String dataFileName, String templateFileName,
                          String outputFileName){

//String tempFile = System.getProperty("user.dir")+"\\src\\test\\util\\";
StringBuffer tempStr = new StringBuffer();
String data = new String();
String[] tempData = new String[7];
String[] result = new String[7];

TransRecordManager transRecMan = new TransRecordManager();
//获取文件data.txt的数据,返回并保存在数组temp中
TransRecord[] tempRec = transRecMan.getAll();

//File dataFile = new File(dataFileName);
File templateFile = new File(templateFileName);
BufferedReader reader = null;
FileWriter outputFile = null;
try {
//读取templateFile中的数据,并保存在字符串tempStr中
reader = new BufferedReader(new FileReader(templateFile));
while(null != (data=reader.readLine())){
tempStr.append(data);
}
//获取template中的数据,并保存在tempStr数组中
int iLast = -1;
int count = 0;
int index = tempStr.indexOf("{");
while (index > 0){
tempData[count++] = tempStr.substring(iLast+1, index);
iLast = tempStr.indexOf("}", index+1);
index = tempStr.indexOf("{", iLast+1);
}

//用数组result保存合并后的结果
for(int i = 0; i < tempRec.length; i++){
result[i] = tempData[0] + tempRec[i].getCustomerNumber()
  + tempData[1] + tempRec[i].getCustomerName()
  + tempData[2] + tempRec[i].getJiGou()
  + tempData[3] + tempRec[i].getSex()
  + tempData[4] + tempRec[i].getAccountNumber()
  + tempData[5] + tempRec[i].getHappenTime()
  + tempData[6] + tempRec[i].getAmount();
//System.out.println(result[i]);
}

//System.out.println(result.length);
File file = new File(outputFileName);
try {
outputFile = new FileWriter(file);
for(int i = 0; i < result.length; i++){
outputFile.write(result[i]);
outputFile.write("\r\n");
outputFile.flush();
}

catch (IOException e) {
e.printStackTrace();


catch (FileNotFoundException e) {
e.printStackTrace();

catch (IOException e1) {
  相关解决方案