2015-05-24 3 views
0

Очень, очень новый для java здесь. В настоящее время у меня есть код для извлечения данных из одного текстового файла и анализа данных в формате, который можно использовать для меня (см. Ниже). К сожалению, для этого мне нужно изменить имя файла для каждого прогона. В идеале я хотел бы автоматизировать его, перейдя через массив строк имен файлов для сбора данных.Java InputData цикл чтения/записи с массивом имен файлов

Любая идея, как я могу передать массив имен файлов и закодировать их через каждое имя?

package weatherfiledata; 


import java.io.*; 

/** 
* 
* 
*/ 
public class WeatherFileData { 
    int month[] = new int[8760]; 
    int day[] = new int[8760]; 
    int hour[] = new int[8760]; 
    int db[] = new int[8760]; 
    int wb[] = new int[8760]; 
    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String[] args) { 
     int count; 
     //here i would declare the array of fileNames and start the loop 
     //String fileNames[] = {"fileName1","fileName2"...}; 
     //for(count = 0; count < fileNames.length; count++){ 


     // TODO code application logic here 
     //create an object named "DataInput" of type "WeatherFileData" 
     WeatherFileData DataInput = new WeatherFileData(); 

     DataInput.InputData(DataInput); 
     //display data 
     int i; 
     for(i=0; i<DataInput.month.length; i++) { 
      System.out.print(DataInput.wb[i] +","); 
     } 
     //} end of loop 
    } 

     void InputData(WeatherFileData DataInput) { 
     BufferedReader br = null; 
     try { 

     String sCurrentLine; 
     //this is where I currently have to change the fileName each time; 
     //I would like to be able to use the fileName array loop to automate 
     br = new BufferedReader(new FileReader("fileName1.txt")); 

     int i=0; 
     while ((sCurrentLine = br.readLine()) != null) { 
      String arr[] = sCurrentLine.split("\t"); 

      DataInput.month[i] = Integer.parseInt(arr[0]); 
      DataInput.day[i] = Integer.parseInt(arr[1]); 
      DataInput.hour[i] = Integer.parseInt(arr[2]); 
      DataInput.wb[i] = Integer.parseInt(arr[3]); 
      DataInput.db[i] = Integer.parseInt(arr[4]); 
      i++; 
     } 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     try { 
      if (br != null)br.close(); 
     } catch (IOException ex) { 
      ex.printStackTrace(); 
     } 
    } 
    } 

} 
+0

Если я правильно понимаю проблему, существует метод '' 'listFiles()' '' в '' 'File''' классе. Вы можете создать файл с каталогом своих файлов, а затем перечислить все файлы внутри. – Mati

+0

Метод listFiles() отлично работает и является очень быстрым и простым способом интеграции этой функции. благодаря! – coolhand

ответ

1

Вы должны начать с введения переменной типа String для имени файла:

br = new BufferedReader(new FileReader(filename)); 

И передать эту переменную в качестве аргумента ваш метод:

void inputData(WeatherFileData dataInput, String filename) { 

Затем вы можете сохранить список этих файлов в массиве:

String[] filenames = new String[5]; 
filenames[0] = "fileName1.txt"; 
... 

И перебирать их с:

for(String filename : filenames){ 
    WeatherFileData dataInput = new WeatherFileData(); 
    dataInput.inputData(dataInput, filename); 
    ... // Do what you want with DataInput 
} 

И как последний комментарий, обратите внимание, что вам не нужно, чтобы сделать это:

dataInput.inputData(dataInput, filename); 

Это было бы лучше:

dataInput.inputData(filename); 

Но внутри функции inputData() написать это:

this.month[i] = Integer.parseInt(arr[0]); 

Вместо этого:

dataInput.month[i] = Integer.parseInt(arr[0]); 

(Я также удалил заглавные первые буквы от вашего объекта и имени метода, который является конвенция)

+0

Большое вам спасибо! И спасибо за исправление моих неправильных правил кодирования! – coolhand

0

Я просто подправили свой код немного. Надеюсь, что это работает

package weatherfiledata; 
import java.io.*; 

/** 
* 
* 
*/ 
public class WeatherFileData { 
    int month[] = new int[8760]; 
    int day[] = new int[8760]; 
    int hour[] = new int[8760]; 
    int db[] = new int[8760]; 
    int wb[] = new int[8760]; 
    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String[] args) { 




     //create an object named "DataInput" of type "WeatherFileData" 
     WeatherFileData dataInput = new WeatherFileData(); 

    String fileNames[] = {"fileName1","fileName2"...}; 
     for(int count = 0; count < fileNames.length; count++){ 
     dataInput.inputData(fileNames[count],count); 

    } 


     //display data 
     int i; 
     for(i=0; i<dataInput.month.length; i++) { 
      System.out.print(dataInput.wb[i] +","); 
     } 
     //} end of loop 
    } 

     void inputData(String fileName, int currentIndex) { 
     BufferedReader br = null; 
     try { 

     String sCurrentLine; 
     //this is where I currently have to change the fileName each time; 
     //I would like to be able to use the fileName array loop to automate 
     br = new BufferedReader(new FileReader(fileName)); 

     int i=0; 
     while ((sCurrentLine = br.readLine()) != null) { 
      String arr[] = sCurrentLine.split("\t"); 

      this.month[currentIndex] = Integer.parseInt(arr[0]); 
      this.day[currentIndex] = Integer.parseInt(arr[1]); 
      this.hour[currentIndex] = Integer.parseInt(arr[2]); 
      this.wb[currentIndex] = Integer.parseInt(arr[3]); 
      this.db[currentIndex] = Integer.parseInt(arr[4]); 

     } 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     try { 
      if (br != null)br.close(); 
     } catch (IOException ex) { 
      ex.printStackTrace(); 
     } 
    } 
    } 

} 
+0

также избегайте массирования массивов с помощью harcoding 8760. Вместо этого вы можете использовать ArrayList –

+0

Благодарим вас за помощь и советы по кодированию! – coolhand

0

Я хотел бы предложить вам что-то более гибкое (Java 7):

package weatherfiledata; 
import java.io.*; 

public class WeatherFileData { 
    int month[] = new int[8760]; 
    int day[] = new int[8760]; 
    int hour[] = new int[8760]; 
    int db[] = new int[8760]; 
    int wb[] = new int[8760]; 

    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String[] args) { 

     // TODO code application logic here 
     //create an object named "DataInput" of type "WeatherFileData" 
     WeatherFileData DataInput = new WeatherFileData(); 

     DataInput.InputData(DataInput, args[0]/*Path to files*/); 
     //display data 
     int i; 
     for (i = 0; i < DataInput.month.length; i++) { 
      System.out.print(DataInput.wb[i] + ","); 
     } 
    } 

    void InputData(WeatherFileData DataInput, String path) { 
     final File[] files = new File(path).listFiles(); 
     if (files != null) { 
      for (File file : files) { 
       try (BufferedReader br = new BufferedReader(new FileReader(file))) { 

        String sCurrentLine; 
        int i = 0; 
        while ((sCurrentLine = br.readLine()) != null) { 
         String arr[] = sCurrentLine.split("\t"); 

         DataInput.month[i] = Integer.parseInt(arr[0]); 
         DataInput.day[i] = Integer.parseInt(arr[1]); 
         DataInput.hour[i] = Integer.parseInt(arr[2]); 
         DataInput.wb[i] = Integer.parseInt(arr[3]); 
         DataInput.db[i] = Integer.parseInt(arr[4]); 
         i++; 
        } 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 
     } 
    } 
} 

И, конечно же, пожалуйста, прочитайте о Java именования конвенции. http://www.oracle.com/technetwork/java/codeconventions-135099.html

Смежные вопросы