2

我有一个文件用来保存我的程序在执行时需要的系统信息。该程序将定期读取并写入它。我该怎么做呢?除其他问题外,我遇到了路径问题

例子

在此处输入图像描述

如果将应用程序部署为可运行的 jar,我如何读取/写入此属性文件

4

3 回答 3

8

看看http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html

您可以利用此类在属性/配置文件中使用您的键=值对

您问题的第二部分,如何构建可运行的 jar。我会用 maven 来做,看看这个:

如何使用 Maven 创建具有依赖关系的可执行 JAR?

和这个 :

http://maven.apache.org/guides/getting-started/maven-in-five-minutes.html

我看到你没有完全使用 Maven 来构建你的项目

于 2012-04-19T21:00:12.953 回答
2

您不能写入作为 ZIP 文件的一部分存在的文件......它不作为文件系统上的文件存在。

考虑过 Preferences API 吗?

于 2012-04-19T21:24:41.737 回答
0

要从文件中读取,您可以使用扫描仪将文件阅读器声明为

Scanner diskReader = new Scanner(new File("myProp.properties"));

之后,例如,如果您想从属性文件中读取布尔值,请使用

boolean Example = diskReader.nextBoolean();

如果您不想写入文件,它会有点复杂,但我就是这样做的:

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;

public class UpdateAFile {

    static Random random = new Random();
    static int numberValue = random.nextInt(100);

    public static void main(String[] args) {
        File file = new File("myFile.txt");
        BufferedWriter writer = null;
        Scanner diskScanner = null;

        try {
            writer = new BufferedWriter(new FileWriter(file, true));
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            diskScanner = new Scanner(file);
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }

        appendTo(writer, Integer.valueOf(numberValue).toString());
        int otherValue = diskScanner.nextInt();
        appendTo(writer, Integer.valueOf(otherValue + 10).toString());
        int yetAnotherValue = diskScanner.nextInt();
        appendTo(writer, Integer.valueOf(yetAnotherValue * 10).toString());

        try {
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    static void appendTo(BufferedWriter writer, String string) {
        try {
            writer.write(string);
            writer.newLine();
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

然后通过以下方式写入文件:

diskWriter.write("BlahBlahBlah");
于 2012-08-05T17:46:15.763 回答