我正在尝试从一个文件夹中读取文件并将其存储在另一个文件夹中,其中包含原始文件名和增加的整数,但我没有成功:
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++;
}
我的所有文件都被移动到0整数的临时文件夹。我需要1,2,3,4 ...... 我错过了什么?
答案 0 :(得分:4)
每次新循环迭代开始时,变量count
都设置为0
。
将声明放在上一行:
int count = 0; //
for (int i = 0; i < listfiles.length; i++) {
答案 1 :(得分:3)
您可能希望在循环的每个回合都不要重新初始化count
到0
...
你基本上有这个:
for (<conditions>) {
int count = 0; // whoops, set to 0 for every iteration!!
// do stuff
count++;
}
你想要这个:
int count = 0;
for (<conditions>) {
// do stuff
count++;
}
i
用于count
。File f = new File(C:/FILES);
在实际代码中明显不同。FileUtils
课程或番石榴的Files
吗?对于Java 5和6.使用try-with-resources,Java 7会更好。
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++;
}