我使用JFrame
Java Swing编写如下代码:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
String filename = (jTextField1.getText());
if (filename.endsWith(".log")) {
Scanner inFile1 = new Scanner(filename).useDelimiter(";");
List<String> temps = new ArrayList<String>();
// while loop
while (inFile1.hasNext()) {
// find next line
String token1 = inFile1.next();
temps.add(token1);
}
inFile1.close();
String[] tempsArray = temps.toArray(new String[0]);
for (String s : tempsArray) {
System.out.println(s);
}
这段代码可以工作,但它只显示文件名作为文件名本身(例如,如果我的文件名= lalala.txt
,控制台的输出将是lalala.txt
),我已经尝试过这段代码,但它不显示文件内的内容。我如何在控制台输出中使用JFrame
作为GUI时显示文件中的内容?我的GUI由一个文本字段组成,它将显示文件名,当我单击jButton2
时,我希望按钮显示文件的内容,而不是文件名本身。它运行得很好,但它不是我想要的输出。
您正在使用:
new Scanner(filename).useDelimiter(";");
依次从字符串filename
中读取数据。而不是使用:
new Scanner(new File(filename)).useDelimiter(";");
直接使用:
try
{
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(new File("absolute path to your text file...")),"UTF8"));
String buf;
while ((buf = in.readLine()) != null)
{
System.out.println(buf);
}
in.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}