2013-11-24 135 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)); 
    } 
}