Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/344.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用JFileChooser创建备份副本_Java_Swing_File Io_Jfilechooser_Datainputstream - Fatal编程技术网

Java 使用JFileChooser创建备份副本

Java 使用JFileChooser创建备份副本,java,swing,file-io,jfilechooser,datainputstream,Java,Swing,File Io,Jfilechooser,Datainputstream,我需要在使用JfileChooser时备份所选文件,以便用户可以指定/或选择备份文件的名称。对于这个过程,我必须使用DataInputStream和DataOutputStream以及readByte和writeByte方法 以下是我到目前为止的情况: public class BasicFile { public BasicFile() throws FileNotFoundException, IOException{ JFileChooser ch

我需要在使用JfileChooser时备份所选文件,以便用户可以指定/或选择备份文件的名称。对于这个过程,我必须使用DataInputStream和DataOutputStream以及readByte和writeByte方法

以下是我到目前为止的情况:

public class BasicFile {        

    public BasicFile() throws FileNotFoundException, IOException{
        JFileChooser chooser = new JFileChooser();
        chooser.showOpenDialog(null);
        File f = chooser.getSelectedFile();            
        if (f.isFile()) 
        {
           DataInputStream dis = new DataInputStream(new FileInputStream(f));
        }
    }        
}

两种流的解决方案:

        DataInputStream dis = new DataInputStream(new FileInputStream(f));
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();

        int nRead;
        byte[] data = new byte[dis.available()];

        while ((nRead = dis.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, nRead);
        }

        buffer.flush();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream dataOutStream = new DataOutputStream(baos);
        dataOutStream.write(data);

        OutputStream outputStream = new FileOutputStream("newFilePath");
        baos.writeTo(outputStream);
        baos.close(); //Lets close some streams 
        dataOutStream.close();
        outputStream.close();
        buffer.close();
        dis.close();
也许有一个较短的解决方案,但上面的代码是有效的

如果没有要求,它将只有一行带有
Files.copy
方法

Files.copy(f.toPath(),新文件(“newFilePath”).toPath(), StandardCopyOption。替换_现有)


所以基本上你想读一个文件,然后把内容复制到另一个文件,是吗?有一大堆样品你可以用谷歌搜索。是的,先生,我试过用谷歌搜索,我真的不知道该怎么做。另一个文件只是所选文件的备份。请看一下如何以多种不同的方式复制文件:我不明白为什么要使用
DataInputStream
DataOutputStream
,但是它们和其他流一样工作。我必须为我正在进行的特定项目使用这两个类。但是谢谢你的帮助!非常感谢。但是我需要了解如何将datainputstream和dataoutputstream与此合并。我更新了我的答案以符合要求。如果这是您问题的正确解决方案,请将答案标记为ACCEPED,以便其他用户可以轻松注意到。