I need to make a backup copy of a selectedfile, while using JfileChooser so that the user can specify/or select the name for the back up file. I have to use DataInputStream and DataOutputStream and the readByte and writeByte methods for this process.

Here is what i have so far:

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));
        }
    }        
}
有帮助吗?

解决方案

Solution with both streams :

        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();

Maybe there is a shorter solution, bute the code aboves works.

Without requirement it would be just one line with the Files.copy method.

Files.copy(f.toPath(),new File("newFilePath").toPath(), StandardCopyOption.REPLACE_EXISTING);

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top