可能重复:
How can a Java program use files inside the .jar for read and write?
如何从JAR java编译的项目写入.txt文件?
当我运行我的项目时,它不会出错,但它不会写入JAR文件中的.txt。
我使用:
制作JAR文件netbeans clean /build tool
public class FileIO {
private File file;
private Scanner filescScanner, lineScanner;
private PrintWriter fileWriter;
private String[][] data;
public FileIO () {
data = new String[100][2];
}
public String[][] getLineScores(){
return this.loadHighscores(this.getClass().getResourceAsStream("LineHighscores.txt"));
}
public String[][] getTimeScores(){
return this.loadHighscores(this.getClass().getResourceAsStream("TimeHighscores.txt"));
}
public void setLineScores( String name,String lines ){
boolean found= false;
data = this.getLineScores();
for(int i = 0; i<data.length && !found ; i++){
if(data[i][0] == null || "Niemand".equals(data[i][0])){
data[i][0]=name;
data[i][1]=lines;
found=true;
}
}
this.saveHighscores(this.getClass().getResource("LineHighscores.txt"),data);
}
public void setTimeScores(String time, String name){
boolean found= false;
data = this.getLineScores();
for(int i = 0; i<data.length && !found ; i++){
if(data[i][0] == null || "Niemand".equals(data[i][0])){
data[i][0]=name;
data[i][1]=time;
found=true;
}
}
this.saveHighscores(this.getClass().getResource("TimeHighscores.txt"),data);
}
private String[][] loadHighscores( InputStream resourceStream){
int x=0;
String test = "";
try{
filescScanner = new Scanner(resourceStream);
}
catch(Exception ioe){
System.err.println(ioe);
}
if (filescScanner.hasNext()){
while(filescScanner.hasNextLine()&& x<100) {
lineScanner = new Scanner(filescScanner.nextLine());
lineScanner.useDelimiter("-/-");
data[x][0]=lineScanner.next();//name
data[x][1]=lineScanner.next();//data
x++;
}
lineScanner.close();
filescScanner.close();
}
else{
data[0][0] = "Niemand";
data[0][1] = "0";
}
return data;
}
private void saveHighscores( URL resourceStream, String[][] data){
int x=0;
try {
file = new File(resourceStream.toURI());
} catch (URISyntaxException ex) {
Logger.getLogger(FileIO.class.getName()).log(Level.SEVERE, null, ex);
}
try {
fileWriter = new PrintWriter(file);
} catch (FileNotFoundException ex) {
Logger.getLogger(FileIO.class.getName()).log(Level.SEVERE, null, ex);
}
if(data.length>x){
while(data.length>x && data[x][0] != null ){
fileWriter.println(data[x][0]+"-/-"+data[x][1]);
x++;
}
fileWriter.close();
}
}
public static void main(String[] args){
FileIO file = new FileIO();
file.setLineScores("55555555", "KoenKevin");
}
}
答案 0 :(得分:9)
你不能这样做,即使你能做到这一点,也不建议:写到罐子外面的位置。
答案 1 :(得分:4)
Jar是一个存档,意思是不变。如果您需要jar(应用程序)来编写内容,请写入外部源。
我建议你创建一个单独的文件夹,让你的应用程序指向该文件夹并在那里进行所有外部活动。
答案 2 :(得分:3)
当您尝试在jar中编写文本文件时,java无法识别文本文件的绝对路径。
它会像
C:User/adom/documents/jarName.jar!/fileName.txt
这不是绝对路径,因此无法写入文件。尝试从外部写文件。