java - 如何拆分列表中的字符串并使用逗号作为分隔符
问题描述
所以我正在读取一个 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;
}
}
}
}
解决方案
推荐阅读
- api - Json 变量没有在 R 管道工包的获取请求中作为参数或响应得到?
- audio - 比特率是多少?
- javascript - 如何访问在严格上下文之外定义的变量?
- c# - 如何将文件从 aspx.cs 类加载到文件组件中?
- javascript - JavaScript:将索引位置返回为 1 而不是 0
- ios - 服务器端未收到 IOS 订阅状态 URL
- python - 如何存储从请求中收到的 cookie?
- vba - Outlook 2016:使用 VBA/宏创建带有签名的会议
- c# - 当应用程序的主视图关闭但辅助视图仍处于打开状态并从开始菜单打开应用程序时,如何恢复 UWP 应用程序的主视图?
- slack - 如何使用机器人将文件上传到松弛通道