首页 > 解决方案 > 如何拆分列表中的字符串并使用逗号作为分隔符

问题描述

所以我正在读取一个 csv 格式的文件,然后对其进行格式化并将其输出到控制台我唯一的问题是它工作正常,直到我点击一个包含空格的字符串,所以我想知道是否有办法读取数据到一个列表中,如果有逗号,则元素递增,所以如果我有这个文本文件我正在读入

000001, 松草, 长底叶, 600.0 000002, Lembas, 精灵旅行面包, 200.0 000003, 酒, 林地精灵酒, 400.0 000004, 蘑菇, 农夫图克的上品, 125.0 000005, 秘银, 魔法矮人盔甲, 3000.0

如果这样做的话,我将如何将长底叶作为一根绳子,因为这是我尝试过的

import java.io.*;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileSystemView;
import java.util.ArrayList;
import java.util.Scanner;

public class ProductReader {
    public static void main (String[] args) {
        ArrayList<String> reader = new ArrayList<String>();
        JFileChooser file = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
        int returnValue = file.showOpenDialog(null);
        int line = 0;
        int end = 0;
        int counterID = 0;
        int counterProduct = 1;
        int counterDescription = 2;
        int counterCost = 3;

        if (returnValue == JFileChooser.APPROVE_OPTION) {
            File selectedFile = file.getSelectedFile();
            String fileName = selectedFile.getName();

            try {
                Scanner fin = new Scanner (selectedFile);

                while (fin.hasNext()) {
                        String data = fin.next();
                        reader.add (data.replace(",", ""));
                }
                fin.close();
            }
            catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }

        System.out.printf ("%s", "ID#");
        System.out.printf ("%15s", "Product");
        System.out.printf ("%15s", "Description");
        System.out.printf ("%15s", "Cost\n");
        System.out.print ("==============================================================\n");

        for (int x = 0; x < reader.size(); x++) { 
            if (line == 0) {
                System.out.printf ("%-9s", reader.get(counterID));
                counterID += 4;
            }

            if (line == 1) {
                System.out.printf ("%-16s", reader.get(counterProduct));
                counterProduct += 4;
            }

            if (line == 2) {
                System.out.printf ("%-18s", reader.get(counterDescription));
                counterDescription += 4;
            }

            if (line == 3) {
                System.out.print (reader.get(counterCost));
                counterCost += 4;
            }

            end++;

            if (reader.size() > end) {
                line++;
            }

            if (line == 4) {
                System.out.println();
                line = 0;
            }
        }
    }
}

标签: java

解决方案


推荐阅读