Reading and writing to file , getting null when i try to  read file content

i start by apologizing incase i have posted this question in the wrong forum
i am trying to iterate through a directory tree and pick all the subdirectories and put them in an arraylist . on the other hand , i am picking all the files and putting them in a different arraylist . After that i iterate through the arraylist , pick a folder , create a file in it search for all the files of the same type in its subfolders and write them to the newly created file
The problem i am running into is i i can't read the files and hence i can't write to the file .
My directory tree is in the format
c:\KPCData\\01\01\01\01\01\ file1_type1
c:\KPCData\\01\01\01\01\02\ file2_type1
where one one of the types is "covers" . i know this could be asking too much but i am at my tethers end , could someone please have a look at the code and tell me where i might be going wrong . you could zero in on the part where i have ************ before the a line of code thank you package directories;
import java.io.*;
import java.util.*;
public class Directories {
private static  ArrayList direcs= new ArrayList();
private static  ArrayList census= new ArrayList();
private static ArrayList vagrant= new ArrayList();
private static ArrayList hotel= new ArrayList();
private static ArrayList emigrant= new ArrayList();
private static ArrayList traveller= new ArrayList();
private static ArrayList longform= new ArrayList();
private static ArrayList cover= new ArrayList();
private static String parentPath = null;
private static File mycover = null;
private static File mytravel = null;
private static File myemigrant = null;
private static File mylong= null;
private static File myinstitution = null;
private static File myvagrant = null;
private static BufferedReader in;
private static BufferedWriter out;
private static String read,toread;
//function for listing the folder contents
class compareDirs implements Comparator
public int compare(Object one, Object two)
     int val=0;
     File file1 = (File)one;
     File file2= (File)two;
     String name1 = file1.toString();
     String name2= file2.toString();
     if (name1.length()==name2.length())
     val= name1.compareTo(name2);
     else
          if( name1.length()>name2.length())
               val=-1;
          if (name1.length()<name2.length())
               val=1;
     return val;
private  ArrayList recurs(File dir,File file) throws IOException
     File []files=dir.listFiles();
     for(int index=0;index<files.length ;index++)
          if(files[index].isDirectory())
               recurs(files[index],file);          
          }//if
          else
              census.add(files[index]);     
     }//for index
     return census;
} //recurs
//function for determining the number and paths of the folders
private ArrayList numDirs(File dirs)
     File []files=dirs.listFiles();
     for(int index=0;index<files.length ;index++)
          if(files[index].isDirectory())
               if (direcs.contains(files[index])==false)
               direcs.add(files[index]);
               numDirs(files[index]);     
          }//if
     }//for index
     return direcs;
public static void main(String[]args) throws IOException
          File myfile = new File("C:\\KPCData");
     File myfile2= new  File("C:\\KPCData\test.txt");
     Directories dir = new Directories();
     if (myfile.isDirectory())
     ArrayList myList=dir.recurs(myfile,myfile2);
     ArrayList mydir1 = dir.numDirs(myfile);
    ArrayList mydirs = new ArrayList();
    mydirs.add(mydir1.get(0));
     for (int x=0;x<mydir1.size();x++)
     {  int count=0;
          for (int y=0;y<mydirs.size();y++)
               if (x==y)
                    count++;
          if (count<1)
               mydirs.add(mydir1.get(x));
     Collections.sort( mydirs,dir.new compareDirs() );     
        for(int index1 =0 ;index1<mydirs.size();index1++)//print out directories
          File mydir=(File)mydirs.get(index1);
          File directory= (File)mydirs.get(index1);
          if(!mydir.getPath().contains("00"))//// if not leave node  create files for each file type
               String name1 =mydir.getPath();
               ArrayList ray=new ArrayList();
               String name="K";
             for (int index=0;index<name1.length();index++ )
                      if (name1.charAt(index)!='\\'&&name1.charAt(index)!='C'&&name1.charAt(index)!=':'&&name1.charAt(index)!='K'&&name1.charAt(index)!='P'&&name1.charAt(index)!='D'&&name1.charAt(index)!='a'&&name1.charAt(index)!='t')
                   name =name+(String.valueOf(name1.charAt(index)));
          // create a string
              name= name.substring(1);
               String trial = name+"_cover.dat";
               mycover = new File ( mydir,trial);
                 if (mycover.exists()) {
                      mycover.delete();
                      mycover.createNewFile();
                  } else {
                       mycover.createNewFile();
                 String addit = mydir.getParent().toString();
                mylong = new File (addit+"\\_long.dat");
                if (mylong .exists()) {
                      mylong.delete();
                      //mylong.createNewFile();
                  } else {
                        //mylong.createNewFile();
                          myemigrant = new File (mydir.getParent()+"\\_emigrant.dat");
                          if (myemigrant.exists()) {
                               myemigrant.delete();
                              // myemigrant.canWrite();
                            } else {
                                 //  myemigrant.canWrite();
               mytravel= new File (mydir.getParent().toString()+"\\_traveller.dat");
                if (mytravel.exists()) {
                    mytravel.delete();
                   // mytravel.createNewFile();
                  } else {
                       //mytravel.createNewFile();
                myinstitution = new File (mydir.getParent().toString()+"\\_institution.dat");
                if (myinstitution.exists()) {
                      myinstitution.delete() ;
                     // myinstitution.createNewFile();
                  } else {
                       //myinstitution.createNewFile();
                myvagrant = new File (mydir.getParent().toString()+"\\_vagrant.dat");
                if (myvagrant .exists()) {
                     myvagrant.delete();
                    // myvagrant.createNewFile();
                  } else {
                       //myvagrant.createNewFile();
     //}//initial
          for( int index2 =0;index2<myList.size();index2++)//loop the second one for individual files
               File file= (File)myList.get(index2);
               if (file.getParent().contains("00"))//leave node
                    parentPath =file.getParent().substring(0, file.getParent().length()-4);
               else
                    parentPath =file.getParent().substring(0, file.getParent().length()-3);
               if (parentPath.toString().compareTo(directory.getParent())==0&file.getName().contains("cover"))
                    try {
                         in = new BufferedReader(new FileReader(file));
                         out = new BufferedWriter( new  FileWriter(mycover));
                    ************     while ((read =in.readLine())!=null)
                         System.out.println("testing");//test whether i ever get in this section !!!
                         out.write(read);               
                         out.close();
                         in.close();
                    catch(NullPointerException e)
                         System.out.println(e);
                    catch(IOException e)
                         System.out.println("There was a problem:" + e);
}//class Directories

kingspalace wrote:
Dr Clap
The problem i am having is that whereas i am very sure that there are contents in the files i am trying to read , this part of the code Print the Values of parentPath,directory.getParent() and file.getName() here .In the start of this if condition to get a idea what stuff is coming here.
if (parentPath.toString().compareTo(directory.getParent())==0&file.getName().contains("cover"))
               {Are you trying to compare parentPath and directory.getParent() as Strings ? How about using equals() ?
Also are you aware that a single & and && are not one and the same ?
& will check nevertheless even if the string comparison on the parentPath returns true or false.
&& will not check file.getName() part if the String comparison part fails.
                    try {
                         in = new BufferedReader(new FileReader(file));
                         out = new BufferedWriter( new FileWriter(mycover));
                    ************     while ((read =in.readLine())!=null)
                         System.out.println("testing");//test whether i ever get in this section !!!
                         out.write(read);               
                         out.close();
                         in.close();
                    catch(NullPointerException e)
                         System.out.println(e);
                    catch(IOException e)
                         System.out.println("There was a problem:" + e);
                         }How about adding a simple Exception catch block here ,in case you miss anything ?
never gets executed executed (meaning ,according to the code, the files am reading have no content ). i am a bit new to files and directories in java . i am hence seeking advice on what i could be doing wrong .IN short,debugging your code will help you a lot.

Similar Messages

  • I received error message to I needed to uninstall  and reinstall due to a registry problem. I did and I am still getting message when I try to open iTunes on my computer.

    I received an error message on my computer when I opened itunes which said due to a registry error I needed to uninstall and reinstall itunes. I have gone through the steps to do that and then reinstalled getting the same message. HELP.

    Hey clueless2661,
    Thanks for using Apple Support Communities.
    If iTunes for Windows won't open, try using the steps.
    iTunes for Windows Vista, Windows 7, or Windows 8: Fix unexpected quits or launch issues
    http://support.apple.com/kb/ts1717
    Have a nice day,
    Mario

  • I updated Itunes today to the latest version. Windows 7 64bit. None of my drivers work and get an error when itunes starts, about registry setting for reading and writing dvds and cds missing. Anyone else have the same issue. I downloaded itunes again, re

    I updated Itunes today to the latest version. Windows 7 64bit. None of my drivers work and get an error when itunes starts, about registry setting for reading and writing dvds and cds missing. Anyone else have the same issue. I downloaded itunes again, reinstalled still have same issue.

    I'd start with the following document, with one modification. At step 12 after typing GEARAspiWDM press the Enter/Return key once prior to clicking OK. (Pressing Return adds a carriage return in the field and is important.)
    iTunes for Windows: "Registry settings" warning when opening iTunes

  • How did my pdf files get converted from 'open with Adobe Reader' to open with Adobe Acobat'?  And if I have a ''free'' Acrobat account why does it not open?  When I do click on the account it ask me to pay $89.99.  I never wanted Acrobat.  How can I get -

    How did my stored files get converted from 'open with Adobe READER' to 'open with Adobe ACROBAT'? How can I get them re-set to open with 'Adobe Reader'?
    Please reply to my e-mail:   [email protected]

    It sounds as if you downloaded Adobe Acrobat Pro. If you did, uninstall it. Then repair Adobe Reader.
    The free Acrobat account has no connection to any of this.

  • Problem on reading and writing from from a *.txt file

    I get Problem on reading and writing from from a *.txt file. The following is the read() method...
    The software said the DataInputStream is depreciated. Can anyone help me please?
    public void read()
        File file = new File("C://Documents and Settings//Charles//My Documents//Brunel//EE2065//Assignment and Lab//Assignment 4 and Lab 4//data.txt");
        FileInputStream in = null;
        String str = "";
        try
          in = new BufferedReader(file);
          //in = new FileInputStream(file);
          for(;;)
            str = new BufferedReader(in).readLine();
            //str = new DataInputStream(in).readLine();
            if(str == null)
              break;
            System.out.print(str);
        in.close();
        catch(IOException e)
            System.err.println("execution error: " +e);
      }

    Thank you for your reply. I have made some change. However, there is an incompetable type found error.
    in = new BufferedReader(new InputStreamReader(in));The following are all of the code.
    public void read()
        File file = new File("C://Documents and Settings//Charles//My Documents//Brunel//EE2065//Assignment and Lab//Assignment 4 and Lab 4//data.txt");
        FileInputStream in = null;
        //BufferedReader in = null;
        String str = "";
        try
          in = new BufferedReader(new InputStreamReader(in));
          //in = new FileInputStream(file);
          for(;;)
            BufferedReader Bstr = new BufferedReader(new InputStreamReader(in));
            //str = new BufferedReader(in).readLine();
            //str = new DataInputStream(in).readLine();
            if(str == null)
              break;
            System.out.print(str);
        in.close();
        catch(IOException e)
            System.err.println("execution error: " +e);

  • File importer detected an inconsistency in the file stucture of (file name). Reading and writing this file's metadata (XMP) has been disabled.

    I have duplicated a project to work on another computer. The project opens fine but when I import new footage/audio files I get this message. "File importer detected an inconsistency in the file stucture of (file name). Reading and writing this file's metadata (XMP) has been disabled." Then I can't play my timeline and Premier Pro crashes.  I have to force quit and restart my computer to continue working. What does this error really mean? How do you rectify?
    Our workflow requires that we duplicate projects to make updates because we are frequently revising but need to keep original project unchanged and intact.

    I have a similar issue and message , but occurs when I import AVI clips from OnLocation CS4 to Premier Pro CS4.

  • I got a new computer and i cant get my music on my phone from iTunes. i got an mp3 file and got it on itunes but when i try to get on my phone nothing happenes. my family have helped me but nothing is working. i don't want to delete anything

    i got an mp3 file and got it on itunes but when i try to get on my phone nothing happenes. my family have helped me but nothing is working. i don't want to delete anything. DONT KNOW WHAT TO DO!!!!!!!!!!!!!

    Yes but all your previous content from the old computer will be erased.
    Read this:
    Syncing to a "New" Computer or replacing a "crashed" Hard Drive

  • File adapter  reading and writing large files

    Hi we are getting error when trying to process large files using file adapters. files of size 80 to 100 MB. we need to read the inbound files and write them to another folder in another server. the error we are getting is out of memory. gracias

    Hi,
    Use the asynchronous process or a checkpoint(); to see your instance before it time-out.
    --Khaleel                                                                                                                                                                                                                           

  • Currently using Flash Pro CS5,  getting error when trying to open CS4 file.  Error is "Slides and Forms documents are not supported in this version of Flash. Please open in previous version.

    Currently using Flash Pro CS5,  getting error when trying to open CS4 file.  Error is "Slides and Forms documents are not supported in this version of Flash. Please open in previous version.  Has there been a fix or patch to this issue or do I have to convert back to CS4 to open the file?

    Having the same problem in CS6.  I can tell you that converting back to CS4 will NOT solve the problem.  It seems when support for backward compatibility is discontinued, there's just no way to get
    any help at all?  Absolute failure to provide any user support so far...

  • When i try to attach files in hotmail, i get a message that silverlight plugin has crashed and error report indicates error about plugin-container.exe ; ihave the latest silverlight plugin. what to do?

    * I work on windows XP
    I have latest fire fox and silver light plugin
    * "silver light plugin has crashed" is what i get when i try to attach files in hotmail
    * error report indicates about plugin-container.exe.
    * where to find plugin-container.exe. to install and try

    Hi,
    Please also try to '''Disable''' the Silverlight add-on in '''Tools '''('''Alt '''+ '''T''') > '''Add-on''' > '''Plugins''' before opening Hotmail. You may still be able to attach files.

  • Reading and Writing large Excel file using JExcel API

    hi,
    I am using JExcelAPI for reading and writing excel file. My problem is when I read file with 10000 records and 95 columns (file size about 14MB), I got out of memory error and application is crashed. Can anyone tell me is there any way that I can read large file using JExcelAPI throug streams or in any other way. Jakarta POI is also showing this behaviour.
    Thanks and advance

    Sorry when out of memory error is occurred no stack trace is printed as application is crashed. But I will quote some lines taken from JProfiler where this problem is occurred:
              reader = new FileInputStream(new File(filePath));
              workbook = Workbook.getWorkbook(reader);
              *sheeet = workbook.getSheet(0);* // here out of memory error is occured
               JProfiler tree:
    jxl.Workbook.getWorkBook
          jxl.read.biff.File 
                 jxl.read.biff.CompoundFile.getStream
                       jxl.read.biff.CompoundFile.getBigBlockStream Thanks

  • Reading and Writing from a text file at the same time

    I know who to use the Scanner and PrintWriter to read from and write to a .txt file. But these are limited. How can I read and write at the same time? Such as open a file and change every third character or change every second word to something else and then write it back. I found this [http://java.sun.com/docs/books/tutorial/essential/io/|http://java.sun.com/docs/books/tutorial/essential/io/] but its a little over my head. Is this the only way to do it?

    wrote:
    You are using buffered reads and writes I would assume, right? Also, how do you think most programs handle this sort of thing? I don't believe I'm using buffering.
    My code looks something like this
    //...necessary imports
    //then
    Scanner inFile = new Scanner (new file("filename1.txt"));
    PrintWriter outFile = new PrintWriter ("filename2.txt");
    //then stuff like
    int x = inFile.hasNextInt();
    outFile.println(x);
    camickr wrote:If you are changing the data "in place", that is none of the data in the file is shifted, then you can use a RandomAccessFile.
    Otherwise, you've been given the answer above.What is RandomAccessFile? Is it what I have a link to? Basically what I do is I write a bunch of numbers to a txt file and then change the numbers I don't need anymore to 0. So say I had 0 1 2 3 4 5 6 7 etc. I would like to to open the txt file and change every second one to 0 so then I'd have only odd numbers and 0s.
    I looked at the documentation for RandomAccessFile and it seems like it might be what I need.
    Thankyou both for your help so far. I took a java course in high school and they only taught me one way to get data from text files and that is what I just showed you. So maybe this questions are really stupid. lol
    Edited by: qw3n on Jun 13, 2009 7:46 PM

  • I bought an eBook from iTunes. I can view/read it perfectly on my iPhone but when I try to open the eBook file on my iPad, I get the error message, "Cannot open book. This book is protected by an incompatible technology." Any ideas for me? thx

    i bought an eBook from iTunes. I can view/read it perfectly on my iPhone but when I try to open the eBook file on my iPad, I get the error message, "Cannot open book. This book is protected by an incompatible technology." Any ideas for me? thx

    Welcome to the Apple Community.
    I have seen previous versions mentioned in a pop up message before on iCloud.com, but I'm not really sure at all how it would help, as I couldn't get it to do anything.
    The best advice I have at this time is to back up your work on your iOS device by regularly saving it to iTunes, if anything goes wrong you can then either load it into the numbers app again on the device or recover it via iTunes on your computer.
    My syncs are immediate, I never get chance to see if it works in the background, sorry.

  • I have the latest Mac Air 13" and I have a Seagate 500MB external hard disk I cant copy or Cut any files on the hard disk and I cant even delete any files. I have the settings as Read and Write in the get info tab. Please help

    I have the latest Mac Air 13" and I have a Seagate 500MB external hard disk I cant copy or Cut any files on the hard disk and I cant even delete any files. I have the settings as Read and Write in the get info tab. Please helpand also note that my hard drive was formatted on a Windows 7 Laptop.

    thats the problem, its in MSDos (Fat) or NTFS for Windows.
    Options.....
    1. offload all that data on the HD onto your PC, THEN format the HD in EXFAT for use on BOTH PC and Mac for read/write.....then reload all (or as you need) that data back onto the HD
    2. get another HD, and format it for Mac OSX extended journaled.
    FAT32 (File Allocation Table)
    Read/Write FAT32 from both native Windows and native Mac OS X.
    Maximum file size: 4GB.
    Maximum volume size: 2TB
    You can use this format if you share the drive between Mac OS X and Windows computers and have no files larger than 4GB.
    NTFS (Windows NT File System)
    Read/Write NTFS from native Windows.
    Read only NTFS from native Mac OS X
    To Read/Write/Format NTFS from Mac OS X, here are some alternatives:
    For Mac OS X 10.4 or later (32 or 64-bit), install Paragon (approx $20) (Best Choice for Lion)
    Native NTFS support can be enabled in Snow Leopard and Lion, but is not advisable, due to instability.
    AirPort Extreme (802.11n) and Time Capsule do not support NTFS
    Maximum file size: 16 TB
    Maximum volume size: 256TB
    You can use this format if you routinely share a drive with multiple Windows systems.
    HFS+     ((((MAC FORMAT)))  (Hierarchical File System, a.k.a. Mac OS Extended (Journaled) Don't use case-sensitive)
    Read/Write HFS+ from native Mac OS X
    Required for Time Machine or Carbon Copy Cloner or SuperDuper! backups of Mac internal hard drive.
    To Read HFS+ (but not Write) from Windows, Install HFSExplorer
    Maximum file size: 8EiB
    Maximum volume size: 8EiB
    You can use this format if you only use the drive with Mac OS X, or use it for backups of your Mac OS X internal drive, or if you only share it with one Windows PC (with MacDrive installed on the PC)
    EXFAT (FAT64)    ------Can read/write from both PC and Mac
    Supported in Mac OS X only in 10.6.5 or later.
    Not all Windows versions support exFAT. 
    exFAT (Extended File Allocation Table)
    AirPort Extreme (802.11n) and Time Capsule do not support exFAT
    Maximum file size: 16 EiB
    Maximum volume size: 64 ZiB
    You can use this format if it is supported by all computers with which you intend to share the drive.  See "disadvantages" for details.

  • IPhone4 how through the USB mobile phone file reading and writing?

    iPhone4 how through the USB mobile phone file reading and writing?

    No idea what you are asking.
    Please explain

Maybe you are looking for

  • Install software for Deskjet 2540 will not load on Windows XP Home edition SP3 machine

    I have successfully connected a new Deskjet 2540 printer to a Windows 7 machine, and IPAD Air, and an XP Pro laptop. I cannot get the install software to load on and XP Home edition SP3 machine. I have tried all of the HP remedies that I can find, ov

  • Download form in word document

    Hi, Can i download the smartform in word document. I know it is possible in PDF, but my requirement is they want that form in word document.

  • OSGi bundle JNI load/unload problem

    Hi everybody!! One more thread about the topic. I still didn't find a solution. Can anybody help me? I have an OSGi bundle that access native methods from a JNI library (for a medical device). I could make my bundle work once, but the second time I t

  • Clean up HTML source

    The company that i work for has recently acquired a new product and I have been assigned to work on the documentation. The legacy docs that we have received ar so big that I've never come across such big help files. For example, there's one project t

  • Torch 9810 slow red flashing light then black screen

    Hi, My phone is over 1 year old, so its not covered by Wind provider warranty. its 15 months now. One day, I plugged into the computer, it was doing an OS update, then froze at 30%. ever since, it is flashing red a few times then nothing... complete