我正在开发一个程序,该程序涉及我必须搜索.txt文件中的特定行并将其中的字符串转换为其他内容。
例如,字符串实际上由数字组成,我想我可以将其转换为整数。主要的是,例如,在第2行,存储了5个数字的邮政编码。我需要将其转换为某些输出,具体取决于数字。换句话说,我需要数字0-9的变量,并根据每个数字输出一个特定的输出。
现在这里是我必须提示用户输入存储在文件中的信息的代码,并且可以读取和打印刚输入的所有信息,但我不确定如何进行其余部分。
import java.io.*;
import java.util.*;
import java.io.FileReader;
import java.io.IOException;
public class ObjectTest2 {
public static void main(String [] args) throws FileNotFoundException, IOException {
// The name of the file to open.
String fileName = "information.txt";
Scanner myScanner = new Scanner(System.in);
try {
// Assume default encoding.
FileWriter fileWriter =
new FileWriter(fileName);
// Always wrap FileWriter in BufferedWriter.
BufferedWriter bufferedWriter =
new BufferedWriter(fileWriter);
// append a newline character.
//This shit here prompts the user for information and stores it in seperate lines to be
//called on by the later section.
System.out.print("What is your name? ");
bufferedWriter.write(myScanner.nextLine());
bufferedWriter.newLine();
System.out.print("What is your 5 digit zip code?");
bufferedWriter.write(myScanner.nextLine());
bufferedWriter.newLine();
System.out.print("What is your +4 digit zip? ");
bufferedWriter.write(myScanner.nextLine());
bufferedWriter.newLine();
System.out.print("What is your address? ");
bufferedWriter.write(myScanner.nextLine());
// Always close files.
bufferedWriter.close();
//reads the information file and prints what is typed
BufferedReader reader = new BufferedReader(new FileReader("information.txt")); {
while (true) {
String line = reader.readLine();
if (line == null) {
break;
}
System.out.println(line);
}
}
}
catch(IOException ex) {
System.out.println(
"Error writing to file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
}
答案 0 :(得分:0)
你别无选择,只能迭代文件的每一行并搜索字符串。如果要根据行号从文件中获取一行字符串,请考虑创建方法。如果需要在同一文件上多次执行操作,并且文件内容没有更改,请使用映射根据行号缓存文件内容。