gpt4 book ai didi

Java GUI 读取具有上述路径的文件

转载 作者:行者123 更新时间:2023-12-01 12:56:58 25 4
gpt4 key购买 nike

JButton btnStart = new JButton("Start");
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {


try{
String filename = fileName.getText();
FileReader fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
Scanner scan = new Scanner(br);
filename = br.readLine();

if (filename != null){

String text = txtKeyword.getText();
String line;
boolean hasError = true;

while ((line = br.readLine()) != null) {

if(line.contains(text)){
String newline = "\n";
jTextArea1.append(line + newline);
hasError = false;
}
}
if (hasError) {

JOptionPane.showMessageDialog(null, "Text Not Found");
br.close();
fr.close();
}
}}catch(IOException e){
JOptionPane.showMessageDialog(null, "File Not Found");
} }
});

因此,在这个函数中,我想通过输入读取提到的目录/文件夹中的一些文本文件。用户使用 JFILECHOOSER 方法选择目录/文件夹,输出将在文本框 [Directory] ​​中列出。假设 fileName 是用户输入文件名的文本字段,用户输入文件名后,单击开始按钮。开始按钮的作用是查找给定的目录/文件夹[文本框]并搜索文本文件并使用system.out.printIn输出文本文件的名称。我还没有尝试过目录/文件夹路径的代码,因为我不确定如何为其编码。对这个问题有什么帮助或指导吗?我只创建了一个类,而且我是 JAVA GUI 新手

完整代码如下:

package com.directory.file;
import java.awt.BorderLayout;
import java.awt.Event;
import java.awt.EventQueue;
import java.awt.TextArea;
import java.awt.TextComponent;
import java.awt.Event.*;
import java.io.FileReader;
import java.io.BufferedReader;
import java.util.Scanner;
import javax.lang.model.element.VariableElement;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.JSpinner;
import javax.swing.SpinnerModel;
import javax.swing.SpinnerNumberModel;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Component;
import java.sql.*;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.JSplitPane;
import javax.swing.JLayeredPane;
import javax.swing.JDesktopPane;
import javax.swing.JComboBox;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.SpinnerDateModel;
import javax.swing.border.CompoundBorder;
import javax.swing.border.LineBorder;
import javax.swing.text.JTextComponent;
import java.awt.Color;
import javax.swing.SwingConstants;
import java.awt.ComponentOrientation;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Calendar;
import com.toedter.calendar.JDateChooser;
import javax.swing.JSpinner;
import org.eclipse.wb.swing.FocusTraversalOnArray;

public class Directory extends JFrame {
private JPanel contentPane;
private JTextField txtKeyword;
private JTextField fileName;
private JTextArea jTextArea1;
private JDateChooser dateChooser;
private JSpinner spinner_1;

public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Directory frame = new Directory();
frame.setVisible(true);
frame.setSize(450,630);
frame.fileName.requestFocus();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Directory() {

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 436, 631);
contentPane = new JPanel();
contentPane.setAlignmentX(Component.LEFT_ALIGNMENT);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);

JLabel lblDirectory = new JLabel("Directory:");
lblDirectory.setBounds(20, 29, 55, 24);
contentPane.add(lblDirectory);

JLabel lblDate = new JLabel("Date:");
lblDate.setBounds(37, 141, 55, 24);
contentPane.add(lblDate);

txtKeyword = new JTextField();
txtKeyword.setHorizontalAlignment(SwingConstants.CENTER);
txtKeyword.setToolTipText("");
txtKeyword.setColumns(10);
txtKeyword.setBounds(85, 193, 229, 20);
contentPane.add(txtKeyword);

final JDateChooser dateChooser = new JDateChooser();
dateChooser.setDateFormatString("YYYMMd");
dateChooser.setBounds(85, 141, 229, 20);
contentPane.add(dateChooser);

JLabel lblKeyword = new JLabel("Keyword:");
lblKeyword.setBounds(20, 191, 55, 24);
contentPane.add(lblKeyword);

JSeparator separator = new JSeparator();
separator.setBounds(148, 204, -113, 34);
contentPane.add(separator);

JButton btnExport = new JButton("Export");
btnExport.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnExport.setBounds(324, 556, 89, 23);
contentPane.add(btnExport);

final JLabel Directory = new JLabel("");
Directory.setBorder(new LineBorder(new Color(0, 0, 0)));
Directory.setBounds(85, 30, 290, 22);
contentPane.add(Directory);

int min = 0;
int max = 23;
int step = 1;
int initValue = 0;
SpinnerModel sm = new SpinnerNumberModel(initValue, min, max, step);
final JSpinner spinner_1 = new JSpinner(new SpinnerNumberModel(0, 0, 23-1, 1));

spinner_1.setBounds(324, 143, 89, 20);
contentPane.add(spinner_1);


JButton btnNewButton = new JButton("...");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {

JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
String filename =f.getAbsolutePath();
Directory.setText(filename);

});
btnNewButton.setBounds(377, 30, 36, 23);
contentPane.add(btnNewButton);

final JTextArea jTextArea1 = new JTextArea();
jTextArea1.setRows(15);
jTextArea1.setColumns(15);
jTextArea1.setBounds(42, 249, 351, 294);
jTextArea1.setLineWrap(true);
jTextArea1.setWrapStyleWord(true);
contentPane.add(jTextArea1);
jTextArea1.setEditable(false);

JButton btnStart = new JButton("Start");
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {


try{
String filename = fileName.getText();
FileReader fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
Scanner scan = new Scanner(br);
filename = br.readLine();

if (filename != null){

String text = txtKeyword.getText();
String line;
boolean hasError = true;

while ((line = br.readLine()) != null) {

if(line.contains(text)){
String newline = "\n";
jTextArea1.append(line + newline);
hasError = false;
}
}
if (hasError) {

JOptionPane.showMessageDialog(null, "Text Not Found");
br.close();
fr.close();
}
}}catch(IOException e){
JOptionPane.showMessageDialog(null, "File Not Found");
} }
});

btnStart.setBounds(324, 215, 89, 23);
contentPane.add(btnStart);


JLabel lblFileName_1 = new JLabel("File Name:");
lblFileName_1.setBounds(20, 79, 75, 24);
contentPane.add(lblFileName_1);


fileName = new JTextField();
fileName.setToolTipText("");
fileName.setHorizontalAlignment(SwingConstants.CENTER);
fileName.setColumns(10);
fileName.setBounds(85, 81, 290, 20);
contentPane.add(fileName);
contentPane.setFocusTraversalPolicy(new FocusTraversalOnArray(new Component[]{fileName, lblDirectory, lblDate, txtKeyword, btnStart, lblKeyword, separator, btnExport, Directory, dateChooser, dateChooser.getCalendarButton(), spinner_1, btnNewButton, jTextArea1, lblFileName_1}));
}
}

最佳答案

问题#1

您仅在尝试打开文件时使用fileName值...

FileReader fr = new FileReader(filename);

文件是目录和名称的串联,例如...

FileReader fr = new FileReader(new File(Directory.getText(), filename));

问题#2

您正在对文件进行某种不需要的抢先读取...

if (filename != null){

String text = txtKeyword.getText();
String line;
boolean hasError = true;

while ((line = br.readLine()) != null) {

您应该开始阅读文件,否则您会丢失第一行文本

问题#3

如果发生某种异常,您不会关闭流...

try {
FileReader fr = new FileReader(new File(Directory.getText(), filename));
BufferedReader br = new BufferedReader(fr);
//...
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "File Not Found");
}

如果由于某种原因,在打开或读取流时发生异常,则它们永远无法关闭......至少在 JVM 关闭之前无法关闭

相反,如果您使用的是 Java 7+,则应该使用 try-with-resources ,或者使用 finally block 来确保流关闭,例如...

BufferedReader br = null;
try {
String filename = fileName.getText();
br = new BufferedReader(new FileReader(new File(Directory.getText(), filename)));
//...
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "File Not Found");
} finally {
try {
br.close();
} catch (Exception e) {
}
}

如果您至少转储实际异常的堆栈跟踪或以某种方式记录它,这也会对您有更多帮助......

} catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "File Not Found");
} finally {

问题#4

null 布局。像素完美布局是现代 UI 设计中的一种幻觉,您无法控制字体、DPI、渲染管道或其他会改变组件在屏幕上渲染方式的因素。

Swing 旨在与布局管理器配合来克服这些问题。如果您坚持忽略这些功能并违背 API 设计,请做好迎接许多头痛和永无休止的艰苦工作的准备......

关于Java GUI 读取具有上述路径的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23799696/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com