现在有一个目录下的多个文件,里面的文件名结构大概是“字符串_0000.扩展名”,我想把里面数字最大的那个文件读出来,下面是我的代码,现在报错,
org.apache.jasper.JasperException: java.lang.NullPointerException
at com.whale.empire.ReadFile.readFile(ReadFile.java:26)
求指教。
- Java code
package com.whale.empire;import java.io.BufferedReader;import java.io.File;import java.io.FileReader;import java.io.IOException;import java.util.ArrayList;public class ReadFile { @SuppressWarnings({ "null", "unchecked" }) public void readFile(String path) throws IOException{ File fl = new File(path); File list[] = fl.listFiles(); String fileName; int [] num = null; int maxIndex = 0; for(int i=0;i<list.length;i++) { if(list[i].isFile()) { fileName = list[i].getName(); int k = fileName.lastIndexOf("."); if((k>-1)&&(k<(fileName.length()))) { num[i] =Integer.parseInt(fileName.substring(k-4,k)); } } } for(int j=0;j<num.length;j++) { int max = num[0]; if(num[j]>max) { max=num[j]; maxIndex = j; } } File file = new File(path+"/"+(list[maxIndex]).getName()); BufferedReader br = new BufferedReader(new FileReader(file)); String currentLine; @SuppressWarnings("rawtypes") ArrayList al = new ArrayList(); while((currentLine = br.readLine())!=null) { al.add(currentLine); } }}
------解决方案--------------------------------------------------------
int [] num = null; 没有初始化数组,应该修改为:
int[] num = new int[list.length];
------解决方案--------------------------------------------------------