Automate opening of sequential files?

0

I want to open multiple binary files in Java at once, but I do not want to instantiate all of them manually in this way as follows. Is there an automatic way, or a method for me to streamline it?

Example:

File arquivo  = new File("temp0.bin");
FileInputStream fis0  = new FileInputStream(arquivo);
DataInputStream dis0  = new DataInputStream(fis0);

arquivo  = new File("temp1.bin");
FileInputStream fis1  = new FileInputStream(arquivo);
DataInputStream dis1  = new DataInputStream(fis1);

arquivo  = new File("temp2.bin");
FileInputStream fis2  = new FileInputStream(arquivo);
DataInputStream dis2  = new DataInputStream(fis2);

arquivo  = new File("temp3.bin");
FileInputStream fis3  = new FileInputStream(arquivo);
DataInputStream dis3  = new DataInputStream(fis3);
    
asked by anonymous 31.08.2017 / 01:37

2 answers

1

This?

ArrayList<File> arquivo = new ArrayList<File>();
ArrayList<FileInputStream> fis = new ArrayList<FileInputStream>();
ArrayList<DataInputStream> dis = new ArrayList<DataInputStream>();
for (int i = 0; i < 4; i++) {
    arquivo.add(new File("temp" + i.toString() + ".bin");
    fis.add(new FileInputStream(arquivo));
    dis.add(new DataInputStream(fis0));
}

Whenever you need to vary something use a variable. Whenever there is a loop, use a loop while or for . If you need to keep multiple states use a array or an list .

    
31.08.2017 / 01:43
0

Something like that? It is possible from Java 7:

File raiz = new File("/home/usuario/Documents/files/");
File[] files = raiz.listFiles();

for (File file : files) {
  if(file.isFile() && file.getName().endsWith(".bin")){
   //   ...
  }
} 

In java 8 you can still use lambdas if you want tb:

Files.newDirectoryStream(Paths.get("."),
    path -> path.toString().endsWith(".bin"))
    .forEach(System.out::println);
    
31.08.2017 / 03:30