繁体   English   中英

打印出特定格式的CSV文件?

[英]printing out csv file in specific format?

我正在读取具有以下布局的csv文件:

CS4092,B
CS2013,A
CS8291,C
CS0927,D
CS0281,A

当我打印出来时,得到以下输出:

CS4092
BMA4042
CCS4023
ACS4075
BCS4010
A

我想要达到的输出是:

CS4092 - B
CS2013 - A
CS8291 - C
CS0927 - D
CS0281 - A

有人可以告诉我我可以通过什么方式获得所需的输出。 谢谢。

public class Student
{
    private String studentID;

public Student()
{

}
    public void setID(String studentID)
    {
        this.studentID = studentID;
    }
public void checkResults() throws IOException 
{
    String lines = "", unparsedFile = "", myArray[];
    String path = System.getProperty("user.home") + 
                             "/NetBeansProjects/CS4013Project/src/" +
                             this.studentID + "Results.csv";
    FileReader fr = new FileReader(path);
    try (BufferedReader br = new BufferedReader(fr)) 
    {
        while((lines = br.readLine()) != null)
        {
            unparsedFile += lines;
        }
    }
   myArray = unparsedFile.split(",");

   for(String item : myArray)
   {
       System.out.println(item);
  }
 }
}

您需要在每对线之间插入逗号,以将它们连接起来形成unparsedFile。

否则,unparsedFile将包含:

CS4092,BCS2013,ACS8291,CCS0927,DCS0281,A

您需要包含以下内容:

CS4092,B,CS2013,A,CS8291,C,CS0927,D,CS0281,A

    int i = 0;
    for (String item : myArray)
    {

        System.out.print(item);//It doent add a new line after printing the item
        if (++i % 2 != 0)
        {
            System.out.println(("-")); //if just one printed just append -
        }
        else
        {
            System.out.println(); //else put a new line and reset the flag
            i=0;

        }
    }

您正在将所有行连接在一起(没有换行符)。 相反,您应该创建一个由行组成的ArrayList<String> ,然后拆分其中的行。

或使用CSV处理库。

尝试将while循环替换为:

while ((lines = br.readLine()) != null) {
   String myarray[] = lines.split(",");
   System.out.format("%s - %s\n", myarray[1],myarray[0]);
}

然后删除代码

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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