我正在尝试写入文件以创建JAR。但是我和NullPointerException
有点问题。我的文件在类路径中。
(我使用getClass()
,因为我将创建一个JAR文件。)
有什么理由让我在这里买NullPointerException
吗?谢谢你的帮助。
代码如下:
package Library;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URISyntaxException;
public class WriteJARSample {
public WriteJARSample() throws URISyntaxException, FileNotFoundException, FileNotFoundException, IOException{
write();
}
public void write() throws URISyntaxException, FileNotFoundException, IOException{
try{
File Mf=new File(getClass().getClassLoader().getResource("AllBookRecords.txt").toURI());
File Tf=new File(getClass().getClassLoader().getResource("Boutput.txt").toURI());
BufferedReader Bbr=new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("AllBookRecords.txt")));
PrintWriter Bpw=new PrintWriter(Mf);
String Bs;
while( (Bs=Bbr.readLine()) != null ){
Bpw.println(Bs);
}
Bpw.close();
Bbr.close();
Mf.delete();
Tf.renameTo(Mf);
}
catch(IOException ioe){
}
catch(URISyntaxException urise){
}
}
public static void main(String[] args) throws URISyntaxException, FileNotFoundException, IOException{
new WriteJARSample();
}
}
发布于 2013-01-20 02:28:27
对于"AllBookRecords.txt“的优先访问,getClass().getResourceAsStream("AllBookRecords.txt")
有所不同,也许它也应该是:
getClass().getClassLoader().getResourceAsStream("AllBookRecords.txt")
或者简单地说
getClass().getResourceAsStream("/AllBookRecords.txt")
getClass().getResource(AsStream)
是相对于类包(子目录)工作的。
https://stackoverflow.com/questions/14417064
复制相似问题