1 Reply Latest reply: Feb 6, 2008 2:58 PM by 796365 RSS

    adding line to txt file and then rename

    807603
      Hello there. I am trying to create a class that will add a line to a txt file and then if the nuber of lines are greater than 5 it will rename the file.

      I think I have solved it with this class.

      My problem is that the file2.renameTo does not work does anyone have any suggestions why?
               public void CopyLines(String string, String location, String fileName) throws IOException {
                   BufferedReader inputStream = null;
                   PrintWriter outputStream = null;
                   
                     GregorianCalendar calendar = new GregorianCalendar(Locale.UK);
                     
                  boolean b=false;
      
                   try {
                       int counter = 0;
                        File file2 = new File(location + fileName);
                        ArrayList arrays = new ArrayList();
      
                        if (file2.exists()){
                       inputStream = 
                           new BufferedReader(new FileReader(file2));
                                          
                       String l;
                       while ((l = inputStream.readLine()) != null) {
                            arrays.add(l);
                           counter++;
                       }
                        } 
                        
                       outputStream = 
                           new PrintWriter(new FileWriter(location + fileName));
                        
                        if (!arrays.isEmpty()){
                             
                             for(int i= 0; i<arrays.size();i++){
                                outputStream.println(arrays.get(i));
                             }
                             
                             
                        }
                        
                       outputStream.println(string);
                       
                       if (counter>5){
                            String newFileName = location + fileName + calendar.getTime().getTime();
                            b = file2.renameTo(new File(newFileName));
                       }
                       
                       
                   } finally {
                       if (inputStream != null) {
                           inputStream.close();
                           
                       }
                       if (outputStream != null) {
                           outputStream.close();
                       }
                   }
               }