2016-06-21 1 views
-1

Je dispose d'un fichier journal CSV et il contient plusieurs lignes comme ceci:Lecture et écriture de fichiers CSV en utilisant Java

2016-06-21 12:00:00,000 : helloworld: header1=2;header2=6;header=0 

Je veux les écrire dans un nouveau fichier CSV.

public void readLogFile() throws Exception 
{ 
    String currentLine = ""; 
    String nextLine = ""; 

    BufferedReader reader = new BufferedReader(new FileReader(file(false))); 
    while ((currentLine = reader.readLine()) != null) 
    { 
     if (currentLine.contains("2016") == true) 
     { 
      nextLine = reader.readLine(); 
      if (nextLine.contains("helloworld") == true) 
      {     
       currentLine = currentLine.substring(0, 23); 
       nextLine = nextLine.substring(22, nextLine.length()); 

       String nextBlock = replaceAll(nextLine); 
       System.out.println(currentLine + " : helloworld: " + nextBlock); 

       String[] data = nextBlock.split(";"); 
       for (int i = 0, max = data.length; i < max; i++) 
       { 
        String[] d = data[i].split("="); 
        map.put(d[0], d[1]); 
       } 
      } 
     } 
    } 
    reader.close(); 
} 

C'est ma méthode pour écrire le contenu:

public void writeContentToCsv() throws Exception 
{ 
    FileWriter writer = new FileWriter(".../file_new.csv"); 
    for (Map.Entry<String, String> entry : map.entrySet()) 
    { 
     writer.append(entry.getKey()).append(";").append(entry.getValue()).append(System.getProperty("line.separator")); 
    } 
    writer.close(); 
} 

Ceci est la sortie que je veux avoir:

header1; header2; header3 
2;6;0 
1;5;1 
5;8;8 
... 

Actuellement, le fichier CSV ressemble à ceci (montrant seulement un ensemble de données):

header1;4 
header2;0 
header3;0 

Quelqu'un peut-il m'aider à corriger le code?

+1

S'il vous plaît utiliser un débogueur et voir où je t va mal – Sanjeev

Répondre

1

Créez une classe pour stocker les valeurs d'en-tête et stockez-la dans la liste. Effectuez une itération sur la liste pour enregistrer les résultats.

La carte actuellement utilisée ne peut stocker 2 valeurs (ce qui est à stocker la valeur d'en-tête (nom de sa valeur correspondante)

map.put (d [0], d [1]); ici d [ 0] sera header1 et d [1] sera 4 (mais nous voulons seulement 4 d'ici)

class Headervalues { 
    String[] header = new String[3]; 
} 

public void readLogFile() throws Exception 
{ 
    List<HeaderValues> list = new ArrayList<>(); 
    String currentLine = ""; 
    BufferedReader reader = new BufferedReader(new FileReader(file(false))); 
    while ((currentLine = reader.readLine()) != null) 
    { 
     if (currentLine.contains("2016") && currentLine.contains("helloworld")) 
     { 

       String nextBlock = replaceAll(currentLine.substring(22, currentLine.length()); 

       String[] data = nextBlock.split(";"); 
       HeaderValues headerValues = new HeaderValues(); 
       //Assuming data.length will always be 3. 
       for (int i = 0, max = data.length; i < max; i++) 
       { 
        String[] d = data[i].split("="); 
        //Assuming split will always have size 2 
        headerValues.header[i] = d[1]; 
       } 
       list.add(headerValues) 
      } 
     } 
    } 
    reader.close(); 
} 
public void writeContentToCsv() throws Exception 
{ 
    FileWriter writer = new FileWriter(".../file_new.csv"); 
    for (HeaderValues value : headerValues) 
    { 
     writer.append(value.header[0]).append(";").append(value.header[1]).append(";").append(value.header[2]); 
    } 
    writer.close(); 
} 
+0

Je dois corriger votre suggestion, mais à part ça, ça a marché! Merci de votre aide! – gpuk360

+0

La solution était de fournir une direction générale, et n'était pas destiné à être un exemple de travail, car je ne suis pas complètement au courant de l'ensemble du code. J'ai essayé de me limiter au code fourni, en faisant des changements minimes. Merci. – Jaiprakash

1

pour écrire au format CSV

public void writeCSV() { 

     // Delimiter used in CSV file 
     private static final String NEW_LINE_SEPARATOR = "\n"; 

     // CSV file header 
     private static final Object[] FILE_HEADER = { "Empoyee Name","Empoyee Code", "In Time", "Out Time", "Duration", "Is Working Day" }; 

     String fileName = "fileName.csv"); 
     List<Objects> objects = new ArrayList<Objects>(); 
     FileWriter fileWriter = null; 
     CSVPrinter csvFilePrinter = null; 

     // Create the CSVFormat object with "\n" as a record delimiter 
     CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR); 

     try { 
      fileWriter = new FileWriter(fileName); 

      csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat); 

      csvFilePrinter.printRecord(FILE_HEADER); 

      // Write a new student object list to the CSV file 
      for (Object object : objects) { 
       List<String> record = new ArrayList<String>(); 

       record.add(object.getValue1().toString()); 
       record.add(object.getValue2().toString()); 
       record.add(object.getValue3().toString()); 

       csvFilePrinter.printRecord(record); 
      } 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       fileWriter.flush(); 
       fileWriter.close(); 
       csvFilePrinter.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    }