2 Replies Latest reply: Sep 14, 2006 8:45 AM by 807598 RSS

    copying one file to another loses a few lines

    807598
      Hello guys

      I have this piece of code which copies a text file at a specific URL to a new file on the user's computer. The text file is very large - 6817 lines - and when it gets copied, the new file only contains 6764 lines.

      Any idea where I may be going wrong?

      Thanks in advance.
      public void copyReport() throws MalformedURLException, IOException {
                      private static URL url;
                   private static URLConnection urlC;
                url = new URL("http://www.someurl.com/subdir1/subdir2/thereport.txt");
                urlC = url.openConnection();          
      
                boolean b = new File("C:\\Copied").mkdir();     
                String localReportPath = "C:\\Copied\\"+getFileName(url.getFile());
                File localReport = new File(localReportPath);
                if (!localReport.exists()) {
                     localReport.createNewFile();     
                } else {
                     localReport.delete();
                     localReport.createNewFile();
                }          
                FileWriter fw = new FileWriter(localReport);          
                InputStream is = url.openStream();               
                InputStreamReader inR = new InputStreamReader(is);
                BufferedReader buf = new BufferedReader(inR);          
                String line;
                while ((line = buf.readLine()) != null ) {
                    fw.write(line+"\n");
                }
                is.close();               
      }
      
      public static String getFileName(String s) {
                String[] parts = s.split("/");     
                return parts[parts.length-1];
      }
        • 1. Re: copying one file to another loses a few lines
          796447
                    is.close();               
          I see that you knew to close this stream, so why did it not occur to you to close the output stream (the FileWriter)?

          And by the way, you should have closed the "buf" stream instead of "is". That will close all of the wrapped input streams, including "is".
          • 2. Re: copying one file to another loses a few lines
            807598
                      is.close();               
            I see that you knew to close this stream, so why did
            it not occur to you to close the output stream (the
            FileWriter)?

            And by the way, you should have closed the "buf"
            stream instead of "is". That will close all of the
            wrapped input streams, including "is".
            bingo! did the job. thanks warnerja.