我目前遇到一个问题。我应该编写一个能够在作为参数给出的 .txt 文件中搜索字符串的程序。程序必须返回找到的字符串的行和列。我正在努力寻找实现这一目标的方法,并且不知道如何继续。我很高兴收到您的来信。
这是我处理我的任务的尝试: - 我考虑过通过缓冲读取器将文件的内容保存在字符串数组中,但这似乎不起作用,因为我无法从一开始就定义数组的长度 - 我还考虑通过缓冲读取器将文件内容保存在字符串中,然后将该字符串拆分为字符。但是我不确定我将如何能够检索原始文件中的行。
这是我目前拥有的非功能代码:
public class StringSearch{
public static void main(String[] args){
if(args.length > 0){
BufferedReader br = null;
String text = null;
try{
br = new BufferedReader(new FileReader(args[0]));
// attempt of saving the content of the "argument" file in a string array and then in a string
String[] lines = new String[]; // I know this does not work like this
for( int i = 0; i < lines.length; i++){
lines[i] = br.readLine;
text = text + lines[i];
i++;
}
text.split("\r\n");
} catch (IOException ioe){
ioe.printStackTrace();
} finally{
if (br != null) {
try{
br.close();
}catch (IOException ioe){
ioe.printStackTrace();
}
}
}
}
}
}