我想读取一个文件并将这些行存储在一个数组中,然后使用 JOptionPane 搜索数组并显示与指定关键字匹配的所有行。
这是我到目前为止所做的:
public class NeedleInHaystack {
public static void main(String[] args) {
JFileChooser jfc = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("jpg", "gif","txt");
jfc.setFileFilter(filter);
int returnCode = jfc.showOpenDialog(null);
if(returnCode == JFileChooser.APPROVE_OPTION);
File f = jfc.getSelectedFile();
System.out.println("You chose to open this file: " +jfc.getSelectedFile().getName());
try {
BufferedReader data;
String aLine;
data = new BufferedReader(new FileReader(jfc.getSelectedFile()));
List<String> lines = new ArrayList<String>();
String UserInPut= JOptionPane.showInputDialog("Please enter a word in your txt");
while((aLine = data.readLine()) != null){
lines.add(aLine);
}
String[] stringArr = lines.toArray(new String[0]);
for(int i=0 ; i < stringArr.length; i++){
System.out.println(aLine);
if (i<=15) { //here just a example, how to do this step
i++;
System.out.println(stringArr[0]);
}
}
data.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:0)
这可以帮到你
public static void main(String[] args) {
JFileChooser jfc = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("jpg", "gif", "txt");
jfc.setFileFilter(filter);
int returnCode = jfc.showOpenDialog(null);
if (returnCode == JFileChooser.APPROVE_OPTION)
;
File f = jfc.getSelectedFile();
System.out.println("You chose to open this file: " + jfc.getSelectedFile().getName());
try {
BufferedReader data;
String aLine;
data = new BufferedReader(new FileReader(jfc.getSelectedFile()));
List<String> lines = new ArrayList<String>();
String UserInPut = JOptionPane.showInputDialog("Please enter a word in your txt");
while ((aLine = data.readLine()) != null) {
lines.add(aLine);
// !!!Output userunput and line of file!!!
if (aLine.contains(UserInPut)) {
System.out.println(UserInPut + " -> " + aLine);
}
}
data.close();
} catch (Exception e) {
e.printStackTrace();
}
}