InputStream help

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • chanshaw
    New Member
    • Nov 2008
    • 67

    #1

    InputStream help

    Ok I'm pretty much copying files in one directory to another the problem I have is that it can only run once, I'm not sure why, possibly I'm forgetting to close a file or something but I can't seem to spot it any advice?

    Code:
        public void copyDirectory() throws Exception
        {
            File listOfFiles[] = directoryA.listFiles();
    
            while(filePosition < listOfFiles.length)
            {
                int len;
                filea = listOfFiles[filePosition];
                InputStream in = new FileInputStream(filea);
                String targetFilePath = directoryB.getAbsolutePath() + "\\" + listOfFiles[filePosition].getName();
                File targetFile = new File(targetFilePath);
                if(targetFile.exists())
                {
                    if(targetFile.lastModified() < filea.lastModified())
                    {
                        OutputStream out = new FileOutputStream(targetFilePath);    
                        byte[] buf = new byte[1024];
                        while ((len = in.read(buf)) > 0)
                        {
                            out.write(buf, 0, len);
                        }
                        in.close();
                        out.close();
                        len = 0;
                    }
                }
                if(!targetFile.exists())
                {
                    OutputStream out = new FileOutputStream(targetFilePath);    
                    byte[] buf = new byte[1024];
                    while ((len = in.read(buf)) > 0)
                    {
                        out.write(buf, 0, len);
                    }
                    in.close();
                    out.close();
                    len = 0;
                }
                filePosition ++;
            }  
        }
  • Aardsquid
    New Member
    • Nov 2008
    • 4

    #2
    It looks to me like you haven't initialized filePosition. Try setting it to 0 at the beginning of the method.

    Comment

    • JosAH
      Recognized Expert MVP
      • Mar 2007
      • 11453

      #3
      This isn't an error but what I personally find very ugly is this:

      Code:
      if(targetFile.exists())
                  {
                      if(targetFile.lastModified() < filea.lastModified())
                      {
                         // copy the file
                      }
                  }
      if(!targetFile.exists())
         // copy the file
      Why not make it like this:

      Code:
      if(!targetFile.exists() || targetFile.lastModified() < filea.lastModified())
         // copy the file
      kind regards,

      Jos

      ps. the previous poster pointed you to the mistake.

      Comment

      Working...