Tobit Sabu
Tobit Sabu

Reputation: 25

Error in reading first element from csv file

I am trying to read a rectangle.csv file in Java. But while I was reading the file and assigning to a string array, the first element is reading some garbage value along with the first element.

package sample;

import java.io.BufferedReader;
import java.io.FileReader;
import java.time.LocalDateTime;

public class rectangleDemo {
    private static Rectangle[] rect ;
    private static int count;
    static private  void loadFile( String filepath) 
    {
        try { // Try catch expression to catch exception
            String info=" ";
             BufferedReader reader =null;            
             reader = new BufferedReader(new FileReader(filepath));

            while ((info = reader.readLine()) != null) 
            {
                 String temp[] = info.split(",");
               //
              System.out.println(temp[0]);
              System.out.println(temp[1]);    
        }
            System.out.println("Database loaded successfully!");
            reader.close();
        }
        catch (Exception e) 
        {
            e.printStackTrace(System.out);
        }
    } 
public static void main(String[] args) {
    // TODO Auto-generated method stub
    loadFile("rectangle.txt");
}

Input file

Output

Upvotes: 1

Views: 1233

Answers (2)

Narayanan Ramanathan
Narayanan Ramanathan

Reputation: 1400

The file 'rectangle.txt' might not be encoded in UTF-8 format. That is why your getting the extra special characters when you read the first line.

You can solve this in two ways,

  1. Change the encoding of rectangle.txt to UTF-8 or
  2. Set the encoding format while reading the file

I just created a UTF-16 file and replicated your issue. The solution would be,

BufferedReader reader =null;     
reader = new BufferedReader(new InputStreamReader(new FileInputStream(filepath),"UTF16"));

Upvotes: 1

Vish
Vish

Reputation: 346

@Tobit, This issue causing while reading the character. So just try setting the correct encoding format while reading the file. Kindly go through this link Reading text file with UTF-8 encoding

Upvotes: 1

Related Questions