java swing获取路径_java swing读取选择的文件内容显示出来到文本框中

选择一个文件后,点读取按钮,就会把内容读取出来显示

// 按读取按钮实现功能

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();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值