我想在 java 中使用代码来读取文本文件,在第一列中选择一个值,然后在第二列中打印其对应的值,如下图所示。
我设法使用此处显示的代码阅读该文件,但我无法继续。
public class readfile {
private Scanner s;
public static void main(String[] args) {
readfile r = new readfile();
r.openFile();
r.readFile();
r.closeFile();
}
public void openFile() {
try {
s = new Scanner (new File("filename.txt"));
} catch(Exception e) {
System.out.println("file not found ");
}
}
public void readFile() {
while(s.hasNext()) {
String a = s.next();
String b = s.next();
System.out.printf("%s %s\n",a, b);
}
}
public void closeFile() {
s.close();
}
}
答案 0 :(得分:0)
以您的代码作为基础(我尝试进行最小的更改)我建议您将读取的值存储在Map中 - 这样可以快速获得相应的值。
public class readfile {
private Scanner s;
public static void main(String[] args) {
readfile r = new readfile();
r.openFile();
//tokens in a map that holds the values from the file
Map<String,String> tokens = r.readFile();
r.closeFile();
//this section just demonstrates how you might use the map
Scanner scanner = new Scanner(System.in);
String token = scanner.next();
//This is a simple user input loop. Enter values of the first
//column to get the second column - until you enter 'exit'.
while (!token.equals("exit")) {
//If the value from the first column exists in the map
if (tokens.containsKey(token)) {
//then print the corresponding value from the second column
System.out.println(tokens.get(token));
}
token = scanner.next();
}
scanner.close();
}
public void openFile() {
try {
s = new Scanner (new File("filename.txt"));
} catch(Exception e) {
System.out.println("file not found ");
}
}
//Note this change - the method now returns a map
public Map<String,String> readFile() {
Map<String, String> tokens = new HashMap<String,String>();
while(s.hasNext()) {
String a = s.next();
String b = s.next();
tokens.put(a,b); //we store the two values in a map to use later
}
return tokens; //return the map, to be used.
}
public void closeFile() {
s.close();
}
}
我希望这说明了如何从文件中读取任何键值对并将其存储起来以供以后使用。