【问题标题】:Saving file as a different name将文件另存为其他名称
【发布时间】:2012-11-26 10:37:12
【问题描述】:

我有一个 Java 表单,您可以在其中选择要打开的文件。我有那个文件:

File my_file = ...

我希望能够将我的文件另存为其他名称。 如何使用“File my_file”来做到这一点?

我试过了:

File current_file = JPanel_VisualizationLogTab.get_File();
String current_file_name = current_file.getName();
//String current_file_extension = current_file_name.substring(current_file_name.lastIndexOf('.'), current_file_name.length()).toLowerCase();
FileDialog fileDialog = new FileDialog(new Frame(), "Save", FileDialog.SAVE);
fileDialog.setFile(current_file_name);
fileDialog.setVisible(true);

但这不会保存文件。

【问题讨论】:

    标签: java file save


    【解决方案1】:

    我建议使用Apache Commons IO 库来简化这项任务。使用这个库,您可以使用方便的FileUtils 类,它提供了许多帮助函数来处理文件 IO。我想你会对copy(File file, File file) 函数感兴趣

    try{
        File current_file = JPanel_VisualizationLogTab.get_File();
        File newFile = new File("new_file.txt");
        FileUtils.copyFile(current_file, newFile);
    } catch (IOException e){
        e.printStackTrace();
    }
    

    Documentation

    【讨论】:

      【解决方案2】:

      如果你想用不同的名字复制它,我通过谷歌找到了这段代码

      public static void copyFile(File in, File out) throws IOException {
          FileChannel inChannel = new FileInputStream(in).getChannel();
          FileChannel outChannel = new FileOutputStream(out).getChannel();
          try {
              inChannel.transferTo(0, inChannel.size(), outChannel);
          } catch (IOException e) {
              throw e;
          } finally {
              if (inChannel != null)
                  inChannel.close();
              if (outChannel != null)
                  outChannel.close();
          }
      } 
      

      现在你可以调用它了

          File inF = new File("/home/user/inputFile.txt");
          File outF = new File("/home/user/outputFile.txt");
          copyFile(inF, outF); 
      

      两个文件都存在很重要,否则会引发异常

      【讨论】:

        【解决方案3】:

        您可以重命名文件名。
        使用:

        myfile.renameTo("neeFile")
        

        【讨论】:

        • 这只有在你想重命名文件并且没有用的情况下才有意义,如果你想拥有它的另一个副本。
        【解决方案4】:

        文件对象有一个名为renameTo(new File("whatever you want"));的方法

        【讨论】:

        • 我需要保留当前文件,并使用不同的名称复制当前文件..
        猜你喜欢
        • 1970-01-01
        • 2021-08-27
        • 1970-01-01
        • 2012-06-28
        • 1970-01-01
        • 2017-05-31
        • 2014-11-26
        • 2016-10-19
        • 1970-01-01
        相关资源
        最近更新 更多