无论程序是从jar还是从IDE运行,如何将文件写入正确的目录?

问题描述 投票:1回答:1

当我的程序以两种不同的方式运行时,我无法写入文本文件。我可以让它在作为jar或NetBeans运行时正常工作,但不能同时运行。

我在Netbeans中添加了我的资源文件夹作为源包,这导致我的程序在IDE中正常工作,但在作为jar运行时却没有。如果我没有我的资源文件夹作为源包,而是将它放在我的项目根文件夹中,它可以从jar正确运行,但不能在IDE中运行。我正在尝试将我的程序转换为java web start应用程序,所以我希望它能同时运行,但如果没有必要,请告诉我。

我首先弄清楚我的代码是否是从jar运行的,所以我可以在将来分离我的逻辑。就目前而言,无论哪种方式都是相同的逻辑。此代码在IDE中有效,但从jar运行时无法保存。 FILEPATH是两个高分文件之一的路径,它看起来像“data / classichighscores.txt”。临时文件是已在同一目录中创建的空文本文件。

  /**
     * saves the data to its own text file.
     */
    public void save() {
        File dataFile = null;
        File tempFile = null;

        String className = this.getClass().getName().replace('.', '/');
        String classJar = this.getClass().getResource("/" + className + ".class").toString();
        if (!classJar.startsWith("jar:")) {
            dataFile = new File(ClassLoader.getSystemResource(FILEPATH).getFile());
            tempFile = new File(ClassLoader.getSystemResource("data/myTempFile.txt").getFile());
        } else {
            dataFile = new File(ClassLoader.getSystemResource(FILEPATH).getFile());           
            tempFile = new File(ClassLoader.getSystemResource("data/myTempFile.txt").getFile());
        }
        try {
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(tempFile), "UTF-8"));

            for (String line : FILEDATA) {
                bw.write(line);
                bw.newLine();
           }

            bw.close();
            dataFile.delete();
            tempFile.renameTo(dataFile);
            tempFile.createNewFile();
        } catch (IOException ex) {
            System.err.println(tempFile.toString());
            System.err.pritnln(dataFile.toString());

我也在过去更改了我的xml文件和清单文件,这可能与我的问题有关。我把这段代码放在同一个分发文件夹中的jar文件和资源中。

<?xml version="1.0" encoding="UTF-8"?>

<project name="TheLostWand" default="default" basedir=".">
    <description>Builds, tests, and runs the project TheLostWand.</description>
    <import file="nbproject/build-impl.xml"/>
    <!--adding resources to dist folder-->
    <target name="-post-jar">
        <mkdir dir="${dist.dir}/resources"/>
        <copy todir="${dist.dir}/resources">
            <fileset dir="${basedir}/resources" />
        </copy>
    </target>

</project>

我添加了Class-Path行。

Manifest-Version: 1.0
X-COMMENT: Main-Class will be added automatically by build
Class-Path: resources/  

我希望我的文本文件可以编辑并保存,并增加了高分。从IDE运行时它可以正常工作,但从jar运行时却没有。我可以从源包中删除我的资源文件夹,它可以从jar工作,但不能从IDE工作。

java jar text-files read-write
1个回答
1
投票

为了保存文本文件,我建议序列化。

//Credit to Jaroslaw Janas
    public void save(String filepath, Object obj) {
//        get the folder
//        if no folder create a new one
        File folder = new File("foldername");
        if (!folder.exists()){
            folder.mkdirs();
        }

        try {
            FileOutputStream file = new FileOutputStream(filepath);
            ObjectOutputStream out = new ObjectOutputStream(file);
            out.writeObject(obj);
            out.close();
            file.close();
        } catch (IOException ex) {
            System.out.println("IOException is caught");
        }
    }

//    this method loades the saved object
//    from a location passed in as an argument
    public Object load(String filepath) {
        Object obj = null;
        try {
            // reading from the file
            FileInputStream file = new FileInputStream(filepath);
            ObjectInputStream in = new ObjectInputStream(file);

            // deserialization
            obj = in.readObject();

            in.close();
            file.close();

        } catch (IOException ex) {
            System.out.println("IOException");
        } catch (ClassNotFoundException ex) {
            System.out.println("ClassNotFoundException");
        }
        return obj;
    }

对于通用目录,%AppData%可能是一个不错的选择。

© www.soinside.com 2019 - 2024. All rights reserved.