我正在尝试使用JFileChooser
选择.txt文件并将其存储在JTextField
中。我将字段命名为txtPath
问题是它没有读取txtPath
。
txtPath.setText(fileChooser.getSelectedFile().toString());
---
public void actionPerformed(ActionEvent evt)
{
File f = new File(txtPath);
int ch;
StringBuffer strContent = new StringBuffer("");
FileInputStream fin = null;
try
{
fin = new FileInputStream(f);
while ((ch = fin.read()) != -1)
strContent.append((char) ch);
fin.close();
}
catch (Exception e)
{
System.out.println(e);
}
System.out.println("Original string: " +strContent.toString()+"\n");
}
答案 0 :(得分:1)
你想:
File f = new File(txtPath.getText());
而不是:
File f = new File(txtPath);
否则,您将为File构造函数提供一个对象引用,而不是JTextField对象中包含的文本。
答案 1 :(得分:0)
我会说使用方法getText()来首先从文本字段中提取字符串