簡體   English   中英

使用JFileChooser和File handlng

[英]Using JFileChooser and File handlng

我無法使用JFileChooser打開文本文件並在控制台中讀取它,我嘗試從一些教程中獲取源代碼,但我只獲得了“文件處理”和“如何使用JFileChooser”的代碼,我試圖將它們組合起來或者只是為了解決這個問題,但我似乎無法做到這一點,我真的沒有想法,任何幫助都會做。

如果JFileChooser返回JFileChooser.APPROVE_OPTION ,則使用.getSelectedFile()將返回File對象

File file;
JFileChooser chooser = new JFileChooer();
int returnValue = JFileChooser.showOpenDialog(this);
if (returnVal = JFileChooser.APPROVE_OPTION){
    file = chooser.getSelectedFile();
}

如果您了解如何使用基本I / O,那么您應該知道如何處理該文件。

相當簡單的東西就是這樣的東西

try {
    BufferedReader in = new BufferedReader(new FileReader(file));
    String line;
    while ((line = in.readLine()) != null){
        textArea.append(line + "\n");
} catch(IOException ex){
    ex.printStackTrace();
}

  • 另一種選擇是使用JTextComponent#read()方法

  • 另一種選擇是使用JEditorPane並使用其setPage()方法

     JEditorPane document = new JEditorPane(); File file = fileChooser.getSelectedFile(); try { document.setPage(file.toURI().toURL()); } catch(Exception e) { e.printStackTrace(); } 

如果您需要I / O的基本幫助,請參閱本教程

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM