[英]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一起做,看看这个:
和这个 :
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.