[英]Java reading file content
Hey I need to read a text file content and store it (for example inside a string). 嘿,我需要阅读文本文件的内容并将其存储(例如,在字符串中)。 The problem is, that I don't want to read a certain file, like here:
问题是,我不想读取某个文件,例如:
btnOpen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
try
{
FileReader reader = new FileReader( "TextAreaLoad.txt" );
BufferedReader br = new BufferedReader(reader);
edit.read( br, null );
br.close();
edit.requestFocus();
}
catch(Exception e2) { System.out.println(e2); }
}
}
I would like to get contains of a file, choosed with fileChooser, like: 我想包含一个文件,该文件是使用fileChooser选择的,例如:
btnOpen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Handle open button action.
if (e.getSource() == btnOpen) {
int returnVal = fc.showOpenDialog(Main.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
}
else {
}
}
}
});
Question is: how? 问题是:如何?
Now that you have the File
, you can create a FileReader
from it and use it just like you do in your first example. 现在有了
File
,您可以从中创建FileReader
并像在第一个示例中一样使用它。 FileReader
has a constructor that takes a File
as a parameter. FileReader
具有将File
作为参数的构造函数。 But I would move the call to the close
method into a finally block. 但是我会将对
close
方法的调用移到了finally块中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.