Question

What I want to do is first of all a kind of copy programm for some files:

You type in a dictory, and somewhere it should be pasted.

Everything works fine, except every filetype that is not .txt ! All the word data can not be opened... all the png, jpg and gif datas can't be opened after the filetransfering!?

So here is what I got:

@SuppressWarnings("deprecation")
static void crypt(String input, String output){
     File folder = new File(input);
     File[] listOfFiles = folder.listFiles();
     for (File file : listOfFiles){
         FileInputStream fis = null;
         BufferedInputStream bis = null;
         DataInputStream dis = null;
         System.out.println("['"+file.getName()+"' is copied]");
         try {
              fis = new FileInputStream(file);

              // Here BufferedInputStream is added for fast reading.
              bis = new BufferedInputStream(fis);
              dis = new DataInputStream(bis);
              FileWriter fstream;
              if(output.endsWith(file.separator) || output.endsWith("/")){  
                  fstream = new FileWriter(output+file.getName());
              }else{
                  fstream = new FileWriter(output+file.separator+file.getName());
              }
              BufferedWriter out = new BufferedWriter(fstream);


              //Close the output stream

              // dis.available() returns 0 if the file does not have more lines.
              while (dis.available() != 0) {

              // this statement reads the line from the file and print it to
                // the console.
                out.write(dis.readLine());
                out.newLine();
              }
              out.close();
              // dispose all the resources after using them.
              fis.close();
              bis.close();
              dis.close();

            } catch (FileNotFoundException e) {
              e.printStackTrace();
            } catch (IOException e) {
              e.printStackTrace();
            }

     }



 }
Was it helpful?

Solution

This

    out.write(dis.readLine());
    out.newLine();

is your problem. Not every file type is line-separated. I would simply perform a byte-by-byte copy in order to preserve the contents. Perhaps you could check out the many IOUtils copy() methods available ?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top