gpt4 book ai didi

java - 如何将我刚刚创建的文件保存在我想要的java文件夹中?

转载 作者:行者123 更新时间:2023-12-02 04:32:44 25 4
gpt4 key购买 nike

所以我有这段代码,我可以在其中创建一个新文件并在其中写入“head.txt”,无论如何,我尝试使 btnNewButton 打开一个 JFileChooser,您可以在其中选择您所在的文件夹想要保存新文件。但它不会起作用。这是我的代码:

    public void actionPerformed(ActionEvent arg0) {
File filenew = new File (".");
try {
String Src = "head.txt";
JFileChooser chooser = new JFileChooser();
chooser.setAcceptAllFileFilterUsed(false);
String choosertitle = "nini";

int result = chooser.showOpenDialog(null);
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle(choosertitle);
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
File selectedfile ;
if (result == JFileChooser.APPROVE_OPTION) {
selectedfile = chooser.getSelectedFile();

String dest = selectedfile + File.separator + textField.getText()+".html";
File fileold = new File (Src);
FileInputStream fileinstr = new FileInputStream(fileold);
BufferedReader br = new BufferedReader(new InputStreamReader(fileinstr));
FileWriter fw = new FileWriter (dest , true);
BufferedWriter out = new BufferedWriter(fw);
String aLine = null;
while ((aLine = br.readLine())!=null){

out.write(aLine);
out.newLine();

}
br.close ();
out.close();
}

}catch (IOException e){
e.printStackTrace();
}

}

这是我的第一个代码,我可以在工作区中创建文件:

try {   File filenew = new File (".");
String Src = "head.txt";
String dest = filenew.getCanonicalPath() + File.separator + textField.getText()+".html";
File fileold = new File (Src);
FileInputStream fileinstr = new FileInputStream(fileold);
BufferedReader br = new BufferedReader(new InputStreamReader(fileinstr));
FileWriter fw = new FileWriter (dest , true);
BufferedWriter out = new BufferedWriter(fw);
String aLine = null;
while ((aLine = br.readLine())!=null){

out.write(aLine);
out.newLine();
}
br.close ();
out.close();


}catch (IOException e){
e.printStackTrace();
}

最佳答案

您在设置属性之前打开了对话框:

int result = chooser.showOpenDialog(null);
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle(choosertitle);
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

应该是:

chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle(choosertitle);
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int result = chooser.showOpenDialog(null);

关于java - 如何将我刚刚创建的文件保存在我想要的java文件夹中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31235348/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com