Art*_*lev 3 java resources jar
我最近写了一个程序.文件处理类是下一个:
package smartest.eu;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Processor {
private BufferedWriter out;
private BufferedReader in;
// this method opens the file for reading!
public void openWriter() throws Exception {
if (out == null) {
try {
out = new BufferedWriter(new FileWriter(new File("src/personaldata.txt")));
}
catch (IOException ex) {
ex.printStackTrace();
}
}
else {
throw new Exception("Writer opened already");
}
}
// this method opens the reader
public void readWriter() throws Exception {
if (in == null) {
try {
in = new BufferedReader(new FileReader("src/personaldata.txt"));
in.mark(65538);
}
catch (IOException ex) {
ex.printStackTrace();
}
}
else {
throw new Exception("Reader already opened");
}
}
// this method reads the file line by line outputting a string as the result
public String readText() throws Exception {
String answer1 = "";
if (in != null) {
try {
if ((answer1 = in.readLine()) != null) {
answer1 += "\n";
}
else {
answer1 = "No more data!\nThe stream will be read from the beginning!\n";
}
}
catch (IOException ex) {
ex.printStackTrace();
}
}
else {
throw new Exception("Open file for reading at first");
}
return answer1;
}
// this method writes the given string to a file
public void writeText(String a) throws Exception {
if (out != null) {
out.write(a);
out.flush();
}
else {
throw new Exception("Open file for writing at first");
}
}
public void resitStream() {
try {
in.reset();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
目录结构processor.jar:
1) manifest
2) personaldata.txt
3) smartest/eu/*.class
Run Code Online (Sandbox Code Playgroud)
但是当我制作jar文件时,它无法找到该文件(提供"File not found exception").我该怎么办呢?PS你能不能提一下这个问题的内容 - 为什么.jar文件在罐子里面不可用?
这条线
new FileReader("src/personaldata.txt")
Run Code Online (Sandbox Code Playgroud)
尝试在当前目录personaldata.txt
的子目录src
中打开该文件.当前目录是在命令提示符中启动java命令时的目录.因此,如果您进入c:\
并启动java -jar the/path/to/myJar.jar
,它将在c:\ src\personaldata.txt中搜索该文件.
因此,文件用于访问文件系统.jar里面没有资源.要从类路径加载资源,必须使用
Processor.class.getResourceAsStream("/personaldata.txt")
Run Code Online (Sandbox Code Playgroud)
请注意,写入jar中的文件是不可能的.