I’m getting weird output when I scan in a csv file split it by “,” ,which for the length of each line I append the ith element with i + “:” to the printwriter.My original input looks something like this.
8.035156 7.619141 7.105469
7.234375 7.8125 8.244141
6.615234 8.224609 6.361328
which they are indeed seperated by “,”.
The output should look something like this
1:8.035156,2:7.619141,3:7.105469,4:7.072266
again it should be seperated by “,”.
but instead the output looks like this, even weirder when i click on the selection it gives me the time.
01:08.0 02:07.6 03:07.1 04:07.1 05:07.4 06:07.2 07:07.6 08:07.1 09:07.1 10:07.2
12:04:06 AM
The wrong output only happens when I add the , character at the end of the append statement.
public class GeneCsv
{
public static void main(String[] args) throws IOException
{
File file = new File("file.csv");
FileWriter writer = new FileWriter("/Users/home/fileExpression.csv");
PrintWriter pw = new PrintWriter(writer);
Scanner in = new Scanner(file);
boolean firstLine = true;
String[] temp = null;
while (in.hasNextLine())
{
if (firstLine == true)
{
pw.println(in.nextLine());
firstLine = false;
continue;
}
else
{
String line = in.nextLine();
temp = line.split(",");
for (int i = 0; i < temp.length; i++)
{
pw.append(i + ":" + temp[i] + ",");
}
pw.append("\n");
}
}
pw.flush();
pw.close();
writer.close();
}
}
There is nothing wrong with your code. The problem is that Excel is interpreting your output as a series of time values. Thus, the value in the first column
1:8.035156is being read as 1 minute, 8.035156 seconds. If you look at the actual data output you’ll see it matches the desired format.To get Excel to treat the values as text you will need to format them as
in the CSV file. The leading
=and surrounding quotes do the trick.See also Stop Excel from automatically converting certain text values to dates