当前位置: 代码迷 >> Java相关 >> Exception in thread "main"不知名的异常!
  详细解决方案

Exception in thread "main"不知名的异常!

热度:3904   发布时间:2013-02-25 21:50:48.0
Exception in thread "main"不知名的错误!!!!
package aa; 

import java.io.BufferedInputStream; 
import java.io.File; 
import java.io.BufferedOutputStream; 
import java.io.IOException
import java.io.FileInputStream; 
import java.io.FileOutputStream; 

public class Util { 

  public Util() { 
  } 

  public static byte[] readFile(String filename) throws IOException

  File file = new File(filename); 
  if (filename == null || filename.equals("")) { 
  throw new NullPointerException("无效的文件路径"); 
  } 
  long len = file.length(); 
  byte[] bytes = new byte[(int) len]; 

  BufferedInputStream bufferedInputStream = new BufferedInputStream(new 
  FileInputStream(file)); 
  int r = bufferedInputStream.read(bytes); 
  if (r != len) { 
  throw new IOException("读取文件不正确"); 
  } 
  bufferedInputStream.close(); 
  return bytes; 
  } 

  public byte[] readFileJar(String filename) throws IOException { 
  BufferedInputStream bufferedInputStream = new BufferedInputStream( 
  getClass().getResource(filename).openStream()); 
  System.out.println(filename); 
  int len = bufferedInputStream.available(); 
  byte[] bytes = new byte[len]; 
  int r = bufferedInputStream.read(bytes); 
  if (len != r) { 
  bytes = null; 
  throw new IOException("读取文件不正确"); 
  } 
  bufferedInputStream.close(); 
  return bytes; 
  } 


  public static void main(String[] args) { 
  Util util = new Util(); 
  try { 
  util.readFile("D:\\XiaoFei\\aaaaaa.txt"); 
  util.readFileJar("D:\\XiaoFei\\aaaaaa.txt"); 

  } catch (IOException ex) { 
  } 
  } 

这是代码! 
以下是错误提示: 
java.lang.NullPointerException 

at aa.Util.readFileJar(Util.java:35) 

at aa.Util.main(Util.java:54) 

Exception in thread "main" 

报错位置: 
BufferedInputStream bufferedInputStream = new BufferedInputStream( 
  getClass().getResource(filename).openStream()); 
util.readFileJar("D:\\XiaoFei\\aaaaaa.txt"); 
不知道是什么错误!!!!求高手解决~

------解决方案--------------------------------------------------------
用文件流试试
------解决方案--------------------------------------------------------
getClass().getResource(filename)这个是要干啥?
------解决方案--------------------------------------------------------
原先的getClass().getResource(filename).openStream() 返回的是null
所以报空指针错误

修改为:
BufferedInputStream bufferedInputStream = new BufferedInputStream( 
new FileInputStream(filename)); 
再试试
------解决方案--------------------------------------------------------
你要这样getClass().getResource(filename)用的话
file必须要在package里,不能用d:\\...访问,要用相对路径
------解决方案--------------------------------------------------------
lz应该去看class getResource()的相关内容 其实目前这个问题算是个classpath的问题
  相关解决方案