Java Buffered Writer到公共可访问的位置

时间:2016-01-08 19:25:45

标签: java bufferedreader filewriter bufferedwriter

我正在尝试更改我刚才写的程序。目前,该程序处理了一些内置了一些逻辑的BufferedReader和BufferedWriters。让我解释一下它是如何工作的。

用于上传文件的类:

public void getFile(){//Used to upload the ACH file. 

        while(uploadApproval==false){//While upload approval has not been given..

        JFileChooser chooser = new JFileChooser();//Creates a new object of the JFileChooser class. 

        uploadFile = chooser;//Saves the upload file variable as the chooser response. 

        FileNameExtensionFilter filter = new FileNameExtensionFilter("ACH Files", "ach");
        //Sets the allowed file formats for upload. 

        chooser.setFileFilter(filter);//Activates the created file filter.

        chooser.setDialogTitle("Please choose ACH file to upload");//Sets the title bar text. 

        //Completes once the user clicks ok. 
        int returnVal = chooser.showOpenDialog(chooser);//
        if(returnVal == JFileChooser.APPROVE_OPTION){
            uploadApproval=true;
        }else{
            System.exit(0);
        }

    }
} 

用于设置目录的类

public void setDirectory(){//Used to set the directory. 

        while(saveApproval==false){//While the user does not have approval of the save location..

        JFileChooser chooser2 = new JFileChooser();//Creates a new JFileChooser object.

        saveFile = chooser2;//Sets the save file location to chooser2. 

        chooser2.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);//User is only able to scan for 
        //directories. 

        //Completes once the user clicks okay. 
        int returnValue2 = chooser2.showDialog(chooser2, "Directory to save");
        if(returnValue2 == JFileChooser.APPROVE_OPTION){
            saveApproval=true;
        }else{
            System.exit(0);
        }

        }

    }

然后我开始实际的缓冲读写器过程,这里涉及很多逻辑:

location = "//NachaOutput"+randomNumber+".ACH";

        try{

            String sCurrentLine;//String representing the current line. 

            //Pulls the uploaded file. 
            br = new BufferedReader(new FileReader(NachaMain.uploadFile.getSelectedFile()));




            bw = new BufferedWriter(new FileWriter(NachaMain.saveFile.getSelectedFile()+location));

现在我需要做的就是这个。我被要求删除用户从头开始选择目录的屏幕。相反,用户将在流程结束时选择保存目录。

这意味着根本不会调用“SetDirectory”方法,因此这行代码:

bw = new BufferedWriter(new FileWriter(NachaMain.saveFile.getSelectedFile()+location));
显然不行。我需要找到一些方法来替换该文件编写器位置的通用位置,对于所有用户而言,无论其设置如何都是相同的。一些文件。

我试过这样做:

bw = new BufferedWriter(new FileWriter("Libraries\\Documents"+location));

但是有一个关于无效路径的例外。

所以请帮帮我,让我知道一条好路径,我可以自动保存文件。保存的文件基本上是一个“虚拟”文件。稍后在程序结束时,我会将该虚拟文件复制到用户指定的位置然后将其删除,因此该位置确实无关紧要。

提前致谢!

1 个答案:

答案 0 :(得分:1)

您可以使用File.createTempFile()创建临时文件。如果为创建的临时文件调用deleteOnExit(),它可能会使清理更容易。