Stanley Mungai
Stanley Mungai

Reputation: 4150

Name fileOutputStream with Incremental Integer

I am attempting to read files from one folder and store then in another folder with the original file name and an increasing integer but i am not succeeding:

File f = new File(C:/FILES);
String listfiles[] = f.list();
for (int i = 0; i < listfiles.length; i++) {
    int count = 0;
    FileInputStream fstemp = new FileInputStream("C:/FILES/" + listfiles[i]);
    FileOutputStream fos = new FileOutputStream("C:/TEMPFILES/" +count + "_"+ listfiles[i]);
    BufferedReader br = new BufferedReader(new InputStreamReader(fstemp));
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
    String strLine;
    ..................
    count++;
}

All my files are being moved to the temp folder with 0 integer. I need 1, 2, 3, 4, ... What am I missing?

Upvotes: 1

Views: 102

Answers (2)

haylem
haylem

Reputation: 22663

You might want to have count not be reinitialized at each turn of the loop to 0...

You have essentially this:

for (<conditions>) {
  int count = 0; // whoops, set to 0 for every iteration!!

   // do stuff

   count++;
}

You want this:

int count = 0;
for (<conditions>) {

   // do stuff

   count++;
}

Extra Notes:

  • I hope you are release those file-handles in finally block somewhere that we don't see.
  • You could use i for count.
  • The example you gave us is incomplete and doesn't work. Please give us a SSCCE. For instance, your File f = new File(C:/FILES); is obviously different in your actual code.
  • If you want to copy files and this isn't homework, may I interest you in Apache Commons's FileUtils class or Guava's Files ?
  • You might want to check that the files don't already exist, and maybe use a temporary folder and temporary file name generator.

Suggested Rewrite

For Java 5 and 6. Java 7 would be nicer with try-with-resources.

int i = 0;

for (final String f : new File("C:/FILES").list()) {
  final FileInputStream fstemp = null;
  FileOutputStream fos = null;

  try {
    fstemp = new FileInputStream(f);
    fos = new FileOutputStream(new File("C:/TEMPFILES/" + i + "_"+ f.getName()));

    // go on with your manual copy code... or use Guava's Files.copy(File, File):
    //   copy(f, new File("C:/TEMPFILES/" + i + "_"+ f.getName()))

    // more stuff here
  } catch (IOException ioe) {
     // catch here if you feel like, and do something about it
  } finally {
     // close streams if not null
  }
  count++;
}

Upvotes: 3

Andremoniy
Andremoniy

Reputation: 34900

You variable count is set to 0 each time new loop iteration begins.

Just put its declaration on the previous line:

int count = 0; //
for (int i = 0; i < listfiles.length; i++) {

Upvotes: 4

Related Questions