Reputation: 4150
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
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++;
}
i
for count
.File f = new File(C:/FILES);
is obviously different in your actual code.FileUtils
class or Guava's Files
?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
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