0

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));
        }
    }        
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Manu
  • 37
  • 4
  • so basically you want to read one file and copy the contents to another file, yes? There is a load of samples you could google for. – Matthias Oct 25 '13 at 06:42
  • yes sir, ive tried googling, im not exactly sure how to go about it really. – Manu Oct 25 '13 at 06:45
  • the other file is just a back up copy of the selected file – Manu Oct 25 '13 at 06:46
  • Have a look here on how to copy files in a lot of different ways: http://stackoverflow.com/questions/2520305/java-io-to-copy-one-file-to-another I do not understand why you have to use `DataInputStream` and `DataOutputStream` for this, but they are working like the other Streams. – Matthias Oct 25 '13 at 06:52
  • i have to use both those classes for this particular project im working on. But thank you for the help! – Manu Oct 25 '13 at 07:00

1 Answers1

2

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

Akkusativobjekt
  • 2,005
  • 1
  • 21
  • 26