簡體   English   中英

Java如何讀取和寫入內部屬性文件?

[英]Java How do I read and write an internal properties file?

我有一個文件,我用來保存我的程序執行時需要的系統信息。 程序將從中讀取並定期寫入。 我該怎么做呢? 在其他問題中,我遇到路徑問題

在此輸入圖像描述

如果將應用程序部署為runnable jar,我該如何讀/寫這個屬性文件

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

您可以利用此類在property / config文件中使用key = value對

問題的第二部分,如何構建一個可運行的jar。 我和maven一起做,看看這個:

如何使用Maven創建具有依賴關系的可執行JAR?

和這個 :

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

我發現你並沒有使用maven來完全構建你的項目

您不能寫入作為ZIP文件的一部分存在的文件...它不作為文件系統上的文件存在。

考慮了Preferences API?

要從文件中讀取,您可以使用掃描儀聲明文件讀取器

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");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM