首页 > 解决方案 > Problems reading/writing in .jar

问题描述

I'm pretty new to jar files and java IO. I'm just making a simple program. Everything works great in IntelliJ but once I create a jar I'm not sure if my problem is reading or writing or creating a file, to begin with... I believe my problem lies in the following two lines once in a jar

saveFile = new File(fileName);
Scanner scanner = new Scanner(SaveFile);

Heres my class:

public class FileWriteRead {

private String fileName;
private File saveFile;
private static String data = "";

public FileWriteRead(String fileName) {
    this.fileName = fileName;
    createFile();
    readFile();
}

public final String getData() {
    return data;
}

private final boolean createFile() {
    try {
        saveFile = new File(fileName);
        if (saveFile.createNewFile()) {
            System.out.println("File " + saveFile.getName() + " created");
            this.fileName = saveFile.getName();
            return true;
        } else {
            System.out.println("File " + fileName + " already exists");
            return false;
        }
    }catch(IOException e){
        System.out.println("Error creating file");
        return false;
    }
}

public final boolean writeToFile(String info){
    try{
        FileWriter writer = new FileWriter(fileName);
        writer.write(info + data );
        writer.close();
        System.out.println("file write successful");

    }catch(IOException e){
        System.out.println("an error occurred");
        return false;
    }
    return true;
}

private final String readFile() {

    try {
        Scanner fileReader = new Scanner(saveFile);
        while(fileReader.hasNextLine()){
            data += fileReader.nextLine();
        }
        System.out.println("File reader created");
        fileReader.close();
        return data;
    }catch(FileNotFoundException e){
        System.out.println("File not found");
        return data;
    }

}

}

UPDATE:

so i added some System.out.println() info to the class above and then ran the jar file from the terminal (using a mac) and weirdly enough it worked and actually saved the info onto a new file it created in user/me/ so here is the info and paths that were printed to the command line when running from terminal:

File Save already exists... Path: /Users/me/Save File reader created /Users/me/Save file write to (Save) successful.... path:/Users/me/Save

weirdly enough it will still NOT work if i startup the jar by opening it directly.

标签: javaintellij-ideajario

解决方案


推荐阅读