简体   繁体   中英

CSV file generated from Java adds unwanted question mark (?)

I am creating a CSV file from Java code. (I also generated HTML and txt files with the same. The problem remains the same.)

The code is as below.

private String writeToFile(StringBuffer csvData, long randomDigits, String type) {
    String fileName = "";
    String filePath = "";
    if ("CSV".equals(type)) {
        filePath = WebConstants.PATH + randomDigits + "CSV.csv";
        fileName = randomDigits + "CSV.csv";
    }
    try {
        BufferedWriter bw = new BufferedWriter(new FileWriter(filePath));
        bw.write(csvData.toString());
        bw.flush();
        bw.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return fileName;
}

Now, when the file is generated, all data looks correct. But at the end of file, there is a question mark (?) which is unwanted. I debugged the code, when the bw.write(csvData.toString()) is called, the value of csvData does not contain the question mark at the end.

This is how I am creating the StringBuffer csvData

private StringBuffer saveAsCVSFile(Vector<XYZVO> list) {

    StringBuffer csvData = new StringBuffer();
    XYZVO VO = null;
    if (list != null) {
        for (int i = 0; i < list.size(); i++) {
            VO = list.get(i);
            csvData.append(VO.getABC()+",");
            csvData.append(VO.getDEF()+",");
            csvData.append(VO.getGHI()+",");
            csvData.append(VO.getJKL()+",");
            csvData.append(VO.getMNO()+"\n");
        }
    }
    return csvData;
}

Here, XYZVO contains all String or int variables.

I also added a code to read the generated file it is as below.

private void checkFileData(String filePath) {
        try {
            BufferedReader br = new BufferedReader(new FileReader(filePath));
            String line = null;
            while((line = br.readLine()) != null) {
                System.out.println("Line X: "+line);
            }
        } catch(FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch(IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

When I check the output of this read code in console, it simply doesn't show the question mark at the end.

If some one has any idea, please inform.

When you close the writer, it would be flushed first. So the flush before the close is not necessary. Try removing that.

I used FileWriter to achieve the same :

try
    {
    FileWriter writer=new FileWriter(csv);
    writer.append("Mobile Number");
    writer.append(',');
    writer.append("Message");
    writer.append(',');
    writer.append("Service");
    writer.append(',');
    writer.append("Time");
    writer.append('\n');


    writer.append(mobileNumber);
    writer.append(',');
    writer.append(message);
    writer.append(',');
    writer.append(service);
    writer.append(',');
    writer.append(time);
    writer.append('\n');

    writer.flush();
    writer.close();
}
catch(Exception e){
    //catch Exception here
}

Using your code

I used your code but its working at my end .......

public static void main(String[] args) throws URISyntaxException, UnknownHostException, ClassNotFoundException{
        Test a = new Test();
        Vector<MyObject> testObj =  new Vector<MyObject>();
        testObj.add(new MyObject());
        testObj.add(new MyObject());
        testObj.add(new MyObject());
        a.checkFileData(a.writeToFile(a.saveAsCVSFile(testObj),123456789 , "CSV"));

    }


    private StringBuffer saveAsCVSFile(Vector<MyObject> list) {

        StringBuffer csvData = new StringBuffer();
        MyObject VO = null;
        if (list != null) {
            for (int i = 0; i < list.size(); i++) {
                VO = list.get(i);
                csvData.append(VO.getABC()+",");
                csvData.append(VO.getDEF()+",");
                csvData.append(VO.getGHI()+",");
                csvData.append(VO.getJKL()+",");
                csvData.append(VO.getMNO()+"\n");
            }
        }
        return csvData;
    }

    private void checkFileData(String filePath) {
        try {

            BufferedReader br = new BufferedReader(new FileReader(filePath));
            String line = null;
            while((line = br.readLine()) != null) {
                System.out.println("Line X: "+line);
            }
            br.close();
        } catch(FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch(IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }



    private String writeToFile(StringBuffer csvData, long randomDigits, String type) {
        String fileName = "";
        String filePath = "";
        if ("CSV".equals(type)) {
            filePath = randomDigits + "CSV.csv";
            fileName = randomDigits + "CSV.csv";
        }
        try {
            BufferedWriter bw = new BufferedWriter(new FileWriter(filePath));
            bw.write(csvData.toString());
            bw.flush();
            bw.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return fileName;
    }


class MyObject{
    static int count =1;

    public String getABC() {
        return "ABC"+(++count);
    }

    public String getMNO() {
        return "MNO"+count;
    }

    public String getJKL() {
        return "JKL"+count;
    }

    public String getGHI() {
        return "GHI"+count;
    }

    public String getDEF() {
        return "DEF"+count;
    }
}

Output

Line X: ABC2,DEF2,GHI2,JKL2,MNO2
Line X: ABC3,DEF3,GHI3,JKL3,MNO3
Line X: ABC4,DEF4,GHI4,JKL4,MNO4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM