选择一个文件后,点读取按钮,就会把内容读取出来显示
// 按读取按钮实现功能
btnNewButton_read.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
// 读取文件路径
String strpath = textField_choose.getText();
System.out.println("strpath22" + strpath);
String res = readFile(strpath);// 读取文本中全部路径
System.out.println("res:" + res);
textArea.setText(res);// 把内容显示到大显示框中
/*mTotalContent = res;// 存入
System.out.println("bb:" + mDestFile);
mDestFile = new File(strpath);// 获取文件路径
System.out.println("33:" + mDestFile);*/
}
});
当然需要写一个方法先(这个我前面讲过):
/*
* *读取文件方法
*/
@SuppressWarnings("resource")
public String readFile(String strpath) {
System.out.println("readFile:" + strpath);
String res = null;
StringBuilder sb = new StringBuilder();
int n = 0;
try {
File file = new File(strpath);
InputStreamReader br = new InputStreamReader(new FileInputStream(file), "UTF-8");
BufferedReader reader = new BufferedReader(br);
String str;
while ((str = reader.readLine()) != null) {
System.out.println("readFiledddd:" + strpath);
sb.append(str + "\n");
System.out.println("55:" + str);
n += 1;
System.out.println("44:" + n);
}
res = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return res;
}
private StringBuffer sb = new StringBuffer();
/*
* 实现写入文件方法
*/
private void writeFile(File file, String content) {
if (file == null || content == null) {
return;
}
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write(content);
writer.flush();
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}