2013-11-24 172 views
-1

我想創建一個方法,將加載一個txt文件,然後改變它,但那是另一種方法。打開一個文件進行編輯

private void openFile() { 
    fileChooser.getSelectedFile(); 
    JFileChooser openFile = new JFileChooser(); 
    openFile.showOpenDialog(frame); 
} 

必須先選擇它來操縱它的數據後,從文件中獲取數據去下一個是什麼?

回答

2

JFileChooser documentation舉例說明如何繼續您的代碼,並獲取所選文件的名稱,然後將其轉換爲File對象。您應該可以修改該示例以滿足您的需求:

JFileChooser chooser = new JFileChooser(); 
FileNameExtensionFilter filter = new FileNameExtensionFilter(
    "JPG & GIF Images", "jpg", "gif"); 
chooser.setFileFilter(filter); 
int returnVal = chooser.showOpenDialog(parent); 
if(returnVal == JFileChooser.APPROVE_OPTION) { 
    System.out.println("You chose to open this file: " + 
     chooser.getSelectedFile().getName()); 
} 
0

下面是一個可能對您有幫助的示例。我想讀一讀,並嘗試一些簡單的例子來讀取和寫入不同的緩衝區。事實上,在過去的幾個月裏,我一直與這些人合作,我仍然需要去看看。

public class ReadWriteTextFile { 
     static public String getContents(File aFile) { 
     StringBuilder contents = new StringBuilder(); 

    try { 
     BufferedReader input = new BufferedReader(new FileReader(aFile)); 
     try { 
     String line = null; //not declared within while loop 
     while ((line = input.readLine()) != null){ 
      contents.append(line); 
      contents.append(System.getProperty("line.separator")); 
     } 
     } 
     finally { 
     input.close(); 
     } 
    } 
    catch (IOException ex){ 
     ex.printStackTrace(); 
    } 
    return contents.toString(); 
    } 

    static public void setContents(File aFile, 
            String aContents) 
             throws FileNotFoundException, 
              IOException { 
    if (aFile == null) { 
     throw new IllegalArgumentException("File should not be null."); 
    } 
    if (!aFile.exists()) { 
     throw new FileNotFoundException ("File does not exist: " + aFile); 
    } 
    if (!aFile.isFile()) { 
     throw new IllegalArgumentException("Should not be a directory: " + aFile); 
    } 
    if (!aFile.canWrite()) { 
     throw new IllegalArgumentException("File cannot be written: " + aFile); 
    } 

     Writer output = new BufferedWriter(new FileWriter(aFile)); 
    try { 
     output.write(aContents); 
    } 
    finally { 
     output.close(); 
    } 
    } 

    public static void main (String... aArguments) throws IOException { 
    File testFile = new File("C:\\Temp\\test.txt");//this file might have to exist (I am not 
                //certain but you can trap the error with a 
                //TRY-CATCH Block. 
    System.out.println("Original file contents: " + getContents(testFile)); 
    setContents(testFile, "The content of this file has been overwritten..."); 
    System.out.println("New file contents: " + getContents(testFile)); 
    } 
}