[英]How to get the data after “=” sign from a txt file?
I have a program, in Java, that will save data to a .txt file and save it like: 我有一个使用Java的程序,它将数据保存到.txt文件并将其保存为:
intdata=2
intdata = 2
stringdata=hello
stringdata =你好
How will I read the data from the text file and specify the value I need. 如何从文本文件中读取数据并指定所需的值。 Lets say I want the intdata value, it would return the part after the equals.
可以说我想要intdata值,它将在等号之后返回该部分。 How do I only return the part after the equals?
我如何仅在相等后退还零件?
If you don't care about the key it's attached to: use String.split
. 如果您不关心它附带的密钥,请使用
String.split
。
Scanner scan = new Scanner(new File("file.txt"));
String value = scan.nextLine().split("=")[1];
If you do care about the key it's attached to: use String.split
in conjunction with a Map
. 如果您确实关心它所附加的键:将
String.split
与Map
结合使用。
Scanner scan = new Scanner(new File("file.txt"));
Map<String, String> values = new HashMap<>();
while(scan.hasNextLine()) {
String[] line = scan.nextLine().split("=");
values.put(line[0], line[1]);
}
Alternatively, if it's a proper .properties
file, you could elect to use Properties
instead: 另外,如果它是正确的
.properties
文件,则可以选择使用Properties
代替:
Properties propertiesFile = new Properties();
propertiesFile.load(new FileInputStream("file.txt"));
// use it like a regular Properties object now.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.