0

I have to run some simulations, the output should be in files, the number of outputs can be changed from simulation to the other, for example, the first simulation I use 10 files, the second will be 14 files. let's say I have N files

I declare the N files using the following instruction:

String path1="C:/Users/Desktop/path1.txt";
File file1 =new File(path1);

to write into the file 1 I use this function:

write(my outputs list,path1,file1);

during the execution, according to some parameters, I select the file to write on it, I would like to do this option without the use of the switch case instruction because it is not easy to manage it if the number of files is big.

with switch case it would be something like:

int choice1 = number;
switch (choice1) {
case 1 :        
write(outputs ,path1,file1);
break;
case 2 :        
    write(outputs ,path2,file2);
break;
case 3 :
.......
}

I would like to replace the switch case with other instruction,

for example, to change the path, I used:

String path= "path"+number;

where number is the number of the path file to write on it. then I can call for my function write(outputs, path, file), but I would like to do the same thing for file, but I do not know how. Please, any help.

jojo
  • 333
  • 2
  • 13
  • 2
    Why can't you do the same thing for file as you do for path? – Tim B Apr 22 '15 at 14:31
  • 2
    What's wrong with passing your `path` you just made to `write`? – Colonel Thirty Two Apr 22 '15 at 14:31
  • because **path** is a 'string' variable, so it is easy to change it by concatenation with any number. – jojo Apr 22 '15 at 14:40
  • I think it could help if you step back for a second and (probably for your self) write down **exactly** how your naming rules/conventions for files/paths should be. Then try to "translate" that to java; if stuck - ask here. Right now, your question isn't really clear what exactly you want to do; or more precisely, if the way you want to do it is really a good solution. – GhostCat Apr 22 '15 at 14:42

3 Answers3

0

You can use 'file.renameTo(someOtherFile)`. This might be important though: Reliable File.renameTo() alternative on Windows?

Community
  • 1
  • 1
0

The path includes filename so include filename in your path String another example, if you want to write files in your app structure:

ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("folder" + number + "/filename" + number + ".xml").getFile());
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
0

If what you wanted was set a filename, like appending a number, maybe you can do something like this:

String name = file.getName();
int pos = name.lastIndexOf(".");
int number = 1;
name = name.substring(0, pos) + number + name.substring(pos, name.length());
jennygii
  • 1
  • 3