1
Select File Dialog Box when Pressing a select button如何在JTextField中使用bufferedreader時顯示Java中的文件路徑?
我需要的文件的絕對路徑是在文本框中。但整個文件內容都在JTextField
。
這裏是我的全碼:
public class NewWork
{
public JFrame Frame;
public JLabel textLabel;
public JButton readButton, writeButton, printButton;
public JTextField textField;
public FileReader reader;
public FileWriter writer;
public BufferedReader br;
public BufferedWriter bw;
public void PrintFrame()
{
Frame = new JFrame();
Frame.setSize(500, 300);
//Frame.pack();
Frame.setBackground(Color.BLUE);
textLabel = new JLabel();
textLabel.setText("Selected File Path:");
textLabel.setBounds(30, 30, 300, 30);
textLabel.setVisible(true);
textField = new JTextField();
textField.setBounds(30, 70, 300, 30);
textField.setVisible(true);
readButton = new JButton();
readButton.setBounds(350, 70, 100, 30);
readButton.setText("Select File");
readButton.setVisible(true);
readButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JFileChooser FileChooser = new JFileChooser();
FileChooser.showOpenDialog(null);
File f= FileChooser.getSelectedFile();
String path= f.getAbsolutePath();
try
{
reader = new FileReader(path);
br = new BufferedReader(reader);
textField.read(br, null);
br.close();
textField.requestFocus();
}
catch(Exception e1)
{
JOptionPane.showMessageDialog(null, e1);
// Check Later
JOptionPane.showMessageDialog(FileChooser, e1);
}
}
});
writeButton = new JButton();
writeButton.setBounds(30, 130, 100, 30);
writeButton.setText("Write");
writeButton.setVisible(true);
writeButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
writer = new FileWriter("E://new.txt");
bw = new BufferedWriter(writer);
textField.write(bw);
bw.close();
textField.setText("");
textField.requestFocus();
}
catch(Exception e2)
{
JOptionPane.showMessageDialog(null, e2);
}
}
});
printButton = new JButton();
printButton.setBounds(190, 130, 100, 30);
printButton.setText("Print Setup");
printButton.setVisible(true);
printButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
boolean complete = textField.print();
if(complete)
{
JOptionPane.showMessageDialog(null, "Done Printing!");
}
else
{
JOptionPane.showMessageDialog(null, " Printing!");
}
}
catch(Exception e3)
{
JOptionPane.showMessageDialog(null, e3);
}
}
});
Frame.add(textLabel);
Frame.add(textField);
Frame.add(readButton);
//Frame.add(writeButton);
Frame.add(printButton);
Frame.setLayout(null);
Frame.setLocationRelativeTo(null);
Frame.setVisible(true);
Frame.setResizable(false);
//
}
public static void main(String[] args)
{
NewWork nw = new NewWork();
nw.PrintFrame();
//System.out.println("Hi");
}
}
好了,你覺得呢'textField.read(BR,空)'幹什麼G? – MadProgrammer
而不是將文件的內容讀取到文本字段,而是簡單地使用File#getAbsolutePath。準備寫入文件時,可以使用[複製文件或目錄](https://docs.oracle.com/javase/tutorial/essential/io/copy.html) – MadProgrammer