JAVA中如何用filechooser选中一个TXT文件后,读取里面的文本内容 然后将其赋给一个string?

2025-04-05 22:29:37
推荐回答(1个)
回答1:

public class JFilechooserDemo{
public static void main(String[] args) throws IOException{
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("Text Files", "txt");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(null);
if(returnVal != JFileChooser.APPROVE_OPTION) {
return;
}

BufferedReader reader=new BufferedReader(new FileReader(chooser.getSelectedFile()));
String line;
StringBuilder sb = new StringBuilder();
while((line=reader.readLine())!=null){
sb.append(line);
}
reader.close();

System.out.println(sb.toString());
}
}