日期:2014-05-20  浏览次数:20777 次

高手帮我看看我这段代码怎么解决空指针异常
package util;

import java.io.File;
import java.util.Vector;

/**
 * 文件工具类
 * 
 * @author marvy
 * 
 */

class Constant(){

public static final String FILE_SEPARATOR = System.getProperty("file.separator");
public static final String LIST_TOKEN = ";";
public static final String PARAMTERS_TOKEN = "&";

public static final String NAME_VALUE_TOKEN = "=";

public static final String PARAMTER_ACTION_KEY = "action";

public static final String ACTION_REGIST = "regist";

public static final String ACTION_LOGIN = "login";

public static final String ACTION_COVER = "cover";

public static final String ACTION_INFO = "info";

public static final String ACTION_LIST = "list";
public static final String ACTION_MUSIC = "music";

public static final String ACTION_DOWNLOAD = "download";

public static final String ACTION_BYE = "bye";

public static final String PARAMETER_FILE_KEY = "file";

}


public class FileUtil {



private FileUtil() {
}

/**
* 是否是指定的音乐格式文件

* @param file 给定文件
* @return 是否
*/
public static boolean isMusicFile(File file) {
if (file == null) {
return false;
}

String name = file.getName().toLowerCase();
if (name.endsWith(".mp3") || name.endsWith(".wma")) {
return true;
}

return false;
}

/**
* 获取给定目录下的所有音乐文件

* @param directory 给定目录
* @return 所有音乐文件
*/
public static Vector getMusicFile(File directory) {
Vector musicFiles = new Vector();
File[] files = directory.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
musicFiles.addAll(getMusicFile(files[i]));
}
if (!FileUtil.isMusicFile(files[i])) {
continue;
}
musicFiles.add(files[i]);
}

return musicFiles;
}

public static String toValidDirectory(String directory) {
if (directory == null) {
return "";
}
if (!directory.endsWith(Constant.FILE_SEPARATOR)) {
directory = directory + Constant.FILE_SEPARATOR;
}

return directory;
}

public static void main(String[] args) {
File file = new File("D:\\musics\\album\\");
System.out.println(getMusicFile(file));
System.out.println(toValidDirectory("kljk"));
}

}


------解决方案--------------------
在File[] files = directory.listFiles();这行增加下面判断
if(files == null){
return musicFiles;
}
还有 Constant后不应该有()
------解决方案--------------------
不知道lz是要干嘛。首先你的class Constant()是不需要括号的 ,其次,D:\\musics\\album\\的路径下是否有mps。wav等格式的文件。
你的报错是for (int i = 0; i < files.length; i++)这个找不到files文件。