Copy files in java

Could you tell me why this " ΓΏ " symbol appears at the end of my output file. (I use try / catch)

File f1 = new File("C:/Users/NetBeansProjects/QuestionOne/input.txt"); File f2 = new File("C:/Users/NetBeansProjects/QuestionOne/output.txt"); fin = new FileInputStream(f1); fout = new FileOutputStream(f2); do { i = fin.read(); fout.write(i); } while (i != -1); 

The code copies the contents of the file, but ends with this strange character. Should I include all the code?

Thanks.

+4
source share
4 answers

The fin.read() method returns -1 when there is nothing to read; but you are actually writing -1 to fout , although this did not happen in fin . It is displayed as this symbol.

One way to write a loop to avoid this problem is to

  while((i = fin.read()) != -1 ){ fout.write(i); } 
+13
source

Because the last fin.read() will not read anything. According to JavaDoc it will return -1 , because of this your fout.write(i) will write this -1 . You would do something similar to fix this behavior:

 do { i = fin.read(); if (i>-1) //note the extra line fout.write(i); } while (i != -1); 

Or change do .. while to call while .. do .

I suggest you also look at the new NIO API, which will work much better than passing one character at a time.

 File sourceFile = new File("C:/Users/NetBeansProjects/QuestionOne/input.txt"); File destFile = new File("C:/Users/NetBeansProjects/QuestionOne/output.txt"); FileChannel source = null; FileChannel destination = null; try { if (!destFile.exists()) { destFile.createNewFile(); } source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } catch (IOException e) { System.err.println("Error while trying to transfer content"); //e.printStackTrace(); } finally { try{ if (source != null) source.close(); if (destination != null) destination.close(); }catch(IOException e){ System.err.println("Not able to close the channels"); //e.printStackTrace(); } } 
+5
source

try using the new Files class introduced in Java 7

 public static void copyFile( File from, File to ) throws IOException { Files.copy( from.toPath(), to.toPath() ); } 
+5
source

or you can just check if (i! = -1) before fout

 do { i = fin.read(); if(i != -1) fout.write(i); } while (i != -1); 
+1
source

Source: https://habr.com/ru/post/1443791/


All Articles