简体   繁体   English

Java BufferedWriter另存为操作

[英]Java BufferedWriter Save As operation

I'm trying to emulate the Save As functionality in Java. 我正在尝试在Java中模拟另存为功能。 I want to choose a filename for it as the code I did before only saved it to 我想为其选择一个文件名,就像之前将其保存到的代码一样

myData.dat

this is used in a menu in my Main.Class which will look up to 这在我的Main.Class的菜单中使用,它将查找

else if (option.compareTo("8") == 0){
    manualLib.save();}


  public void save(){
    String content = "";
    for (int i = 0; i < library.size(); i++){
        for (int bar = 0; bar < library.get(i).size(); bar++){
            content += library.get(i).get(bar).getSerial() + "\n";
            content += library.get(i).get(bar).getTitle() + "\n";
            content += library.get(i).get(bar).getAuthor() + "\n";
            content += library.get(i).get(bar).onLoan() + "\n";
            content += library.get(i).get(bar).getBorrower() + "\n";
        }
    }

    Writer output;
    try {
        output = new BufferedWriter(new FileWriter("myData.dat"));
        try {
              output.write(content);
            }
        finally {
              output.close();
              System.out.println("Successfully saved to myData.dat file.");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

What is a good way of achieving this? 什么是实现这一目标的好方法?

You could use a JFileChooser . 您可以使用JFileChooser This will give you an "easy" UI to let the user choose a file (or a filename). 这将为您提供一个“简单”的用户界面,让用户选择文件(或文件名)。 Then you will substitute your myData.dat with the value returned by chooser.getSelectedFile().getName() . 然后,将您的myData.dat替换为chooser.getSelectedFile().getName()返回的值。

I have not compiled this but your code should in the end look something like: 我还没有编译它,但是您的代码最终应该看起来像:

public void save(){
    String content = "";
    for (int i = 0; i < library.size(); i++){
        for (int bar = 0; bar < library.get(i).size(); bar++){
            content += library.get(i).get(bar).getSerial() + "\n";
            content += library.get(i).get(bar).getTitle() + "\n";
            content += library.get(i).get(bar).getAuthor() + "\n";
            content += library.get(i).get(bar).onLoan() + "\n";
            content += library.get(i).get(bar).getBorrower() + "\n";
        }
    }

    Writer output;

    JFileChooser chooser = new JFileChooser();
    DatFilter filter = new DatFilter();
    filter.addExtension("dat");
    filter.setDescription(".dat files");
    chooser.setFileFilter(filter);
    int returnVal = chooser.showOpenDialog(null);
    String fileName = new String();
    if(returnVal == JFileChooser.APPROVE_OPTION) {
    fileName=chooser.getSelectedFile().getName();
    }

    try {
        output = new BufferedWriter(new FileWriter(fileName));
        try {
              output.write(content);
            }
        finally {
              output.close();
              System.out.println("Successfully saved to "+fileName+" file.");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Then make also class 然后上课

public class DatFilter extends FileFilter {

    //should accept only dirs and .dat files
    public boolean accept(File f) {
        if (f.isDirectory()) {
            return true;
        }

    String extension = null;
        String s = f.getName();
        int i = s.lastIndexOf('.');

        if (i > 0 &&  i < s.length() - 1) {
            extension = s.substring(i+1).toLowerCase();
        }

        if (extension != null) {
            if (extension.equals("dat"){
                    return true;
            } else {
                return false;
            }
        }

        return false;
    }

    //The description of this filter
    public String getDescription() {
        return ".dat Files";
    }
}
  • Use a JFileChooser or whatever UI of your choice to get a full path to the target file to create. 使用JFileChooser或您选择的任何UI来获取要创建的目标文件的完整路径。
  • add a parameter to your save method to get this path, and use it instead of myData.dat save方法中添加参数以获取此路径,并使用它代替myData.dat
  • store the file path in a field of Main.class 将文件路径存储在Main.class的字段中
  • add a save without parameter, that calls the save parameter using the path stored in Main.class. 添加一个不带参数的save ,它使用Main.class中存储的路径调用save参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM