10

I am writing a parser code to read a .csv file and parse it to XML. This is the code I have and it works, except I would like it to skip the first line in the file. So I decided to set up a HashMap but it doesn't seem to work:

for (int i = 0; i < listOfFiles.length; i++) {
        File file = listOfFiles[i];
        if (file.isFile() && file.getName().endsWith(".csv")){
        
            System.out.println("File Found: " + file.getName());//Prints the name of the csv file found

            String filePath = sourcepath + "\\" + file.getName();

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


String line;
int n = 1;
Map<Integer,String> lineMap = new HashMap<Integer,String>();
int k=2;
while ((line = br.readLine()) != null) {
    System.out.println(n + " iteration(s) of 1st While Loop");
    
                    lineMap.put(k, line);

    fw.write("          <ASSET action=\"AddChange\">\n");
    fw.write("              <HOSTNAME>\n");
    hostName=line.substring(0, line.indexOf(","));
    fw.append(hostName);
    fw.write("</HOSTNAME>\n");
    fw.write("              <HOSTID>\n");
    hostID=line.substring(line.indexOf(",")+1, nthOccurrence(line, ',', 1));
    fw.append(hostID);
    fw.write("</HOSTID>\n");
    fw.write("              <MACMODEL>\n");
    machineModel=line.substring(nthOccurrence(line, ',', 1)+1, nthOccurrence(line, ',', 2));
    fw.append(machineModel);
    fw.write("</MACMODEL>\n");
    fw.write("              <PROMODEL>\n");
    processorModel=line.substring(nthOccurrence(line, ',', 2)+1, nthOccurrence(line, ',', 3));
    fw.append(processorModel);
    fw.write("</PROMODEL>\n");
    fw.write("              <CORE>\n");
    core=line.substring(nthOccurrence(line, ',', 3)+1, nthOccurrence(line, ',', 4));
    fw.append(core);
    fw.write("</CORE>\n");
    fw.write("              <PROC>\n");
    proc=line.substring(nthOccurrence(line, ',', 4)+1, nthOccurrence(line, ',', 5));
    fw.append(proc);
    fw.write("</PROC>\n");
    fw.write("              <TIER>\n");
    tier=line.substring(nthOccurrence(line, ',', 5)+1, nthOccurrence(line, ',', 6));
    fw.append(tier);
    fw.write("</TIER>\n");
    fw.write("              <PRODNAME>\n");
    productName=line.substring(nthOccurrence(line, ',', 6)+1, nthOccurrence(line, ',', 7));
    fw.append(productName);
    fw.write("</PRODNAME>\n");
    fw.write("              <VERSION>\n");
    version=line.substring(nthOccurrence(line, ',', 7)+1, nthOccurrence(line, ',', 8));
    fw.append(version);
    fw.write("</VERSION>\n");
    fw.write("              <SCRIPTDATA>\n");
    scriptData=line.substring(nthOccurrence(line, ',', 8)+1, line.length());
    fw.append(scriptData);
    fw.write("</SCRIPTDATA>\n");
    

  fw.write("            </ASSET>\n");
  k++;
}n++;

This is a snippet of the main part of the code. Any Ideas or Solutions???

3
  • Not your down-voter, but clarify your "it does seem to work", please. Commented Aug 19, 2013 at 4:16
  • sorry typo....it doesn't seem to work Commented Aug 19, 2013 at 4:20
  • We know that, but in the future, tell more about how it doesn't work. The more useful information you give, the easier it will be to answer your questions. Commented Aug 19, 2013 at 4:30

10 Answers 10

33

You might consider placing headerLine = br.readLine() before your while loop so you consume the header separately from the rest of the file. Also you might consider using opencsv for csv parsing as it may simplify your logic.

Sign up to request clarification or add additional context in comments.

Comments

15

I feel compelled to add a java 8 flavored answer.

List<String> xmlLines = new BufferedReader(new FileReader(csvFile))
    .lines()
    .skip(1) //Skips the first n lines, in this case 1      
    .map(s -> {
        //csv line parsing and xml logic here
        //...
        return xmlString;
    })
    .collect(Collectors.toList());

Comments

7

Create a variable interation and initialize with 0. Check it as very first thing in while loop.

String line;
int iteration = 0;
while ((line = br.readLine()) != null) {
    if(iteration == 0) {
        iteration++;  
        continue;
    }
    ...
    ...
}

2 Comments

What if I wanted to skip the first two lines? one line with text and the next line is an empty row/whitespace?
@KalaJ: Do if(iteration == 0 || iteration == 1) instead or even better if(iteration < 2). Got it?
2

I am rather confused by your code, your have the lineMap and you also have fw (whatever that is). Which one are you using? You say you want to skip the first line, but you don't

if (firstLine == true) {
   firstLine = false;
   continue;
}

I would also suggest using a library like CSVReader which I belive even has a property ignoreFirstLine

http://opencsv.sourceforge.net/apidocs/au/com/bytecode/opencsv/CSVReader.html

Comments

2

why don't you just use the for loop

for(int i=1; (line = br.readLine()) != null; i++)
{
    //Your code
}

1 Comment

How initializing i=1 will read from second line, there is no control on a variable i, using i is obsolete here.
2

An easy technique, declare a variable and assign it a value (e.g. int k = 0;), and increment the variable value right after you enter into the loop. The code is given below.

BufferedReader csvReader = new BufferedReader(new FileReader("mycsv.csv"));
        // declare a variable
        int k=0;
        while ((row = csvReader.readLine()) != null) {
            if(k == 0){
                k++;
                continue;
            }
         //rest of your code 
         // inside while loop
        }

Comments

0

Use buffer reader two times, like this:

while ((line = br.readLine()) != null) {
  while ((line = br.readLine()) != null) {
    //your code                     
  }
}

Comments

0
boolean isRecord = false;
for (CSVRecord record : records) {
    if(isRecord){
        //process records here.
    }else{
        isRecord = true;
    }
}

Instead of adding counter adding flag will not hit the performance.

Comments

0

A simple solution, read the first line outside of the loop

        String[] nextLine;
        String[] headerLineInCSVFile = csvReader.readNext();
        while ((nextLine = csvReader.readNext()) != null) {
            String columnOne = nextLine[0];
        }

Comments

-1

For skipping first line(which normally contains header of the columns) take a variable and increase this variable in while loop at first place, and continue;

int lineNumber = 0;

and then in while loop 

while ((line = br.readLine()) != null) {
                        if(lineNumber == 0) {
                            lineNumber++;
                            continue;
                        }
                        lineNumber++;

                       //do waterver u have to do with the tokens in this line(second line)

            }

1 Comment

The same basic answer was posted more than a year ago.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.