在Java中对CSV文件的读取感到困惑。

huangapple go评论72阅读模式
英文:

Confused about reading from csv file in java

问题

所以,我目前正在进行一个项目,我正在为一家汽车经销商创建一个库存清单。
我的意图是有一个名为Cars.csv的csv文件,软件从中读取并将其加载到GUI字段中。

我对如何从这个文件中读取感到非常困惑,我希望能直接访问特定的记录。我知道这是一个二维数组。我只是不确定如何设置这整个过程。我的打算是还创建一个名为Cars的类,并为它赋予属性。

如果有人能在任何方面给我建议,请告诉我。请查看这张图片。
csv文件

我以为应该有一种像row1、column4这样的方式来读取它,就像操作数组一样。

英文:

So, I currently am doing a project where I'm creating a stocklist for a car dealership.
My intention was to have a csv file named Cars.csv in which the software reads from it and loads this into the GUI fields.

I'm really confused on how to read from this file, I want to directly access certain records. I understand it's a 2D array also. I'm just confused on how to set this whole thing up. My intention was to have a class named Cars also, and giving it attributes.

If anyone could advise me on anything please let me know. Please look at this image.
csv file

I thought there would be a way to read it like row1, column4, just like an array.

答案1

得分: 1

方法应该如下。

  1. 尝试将文件作为输入流读入您的应用程序。
  2. 读取该输入流的每一行。
  3. 使用“,”拆分该行为数组。

这样,您将能够将 CSV 文件的内容读入您的应用程序。

我还会展示一段示例代码。

FileReader fileReader = new FileReader(file)
BufferedReader br = new BufferedReader();

Map<String, String[]> lines = new HashMap<String, String[]>();
String line;
while ((line = br.readLine()) != null) {
    String[] lineContent= line.split(",");
    // 根据需要使用这个内容
    lines.put(lineContent[0], lineContent);
}

现在,当您想要获取包含“LA1 ABC”的行时,只需调用 lines.get("LA1 ABC")

英文:

Approach should be as follows.

  1. Try reading a file as an input stream into you application.
  2. Read each line for that input stream.
  3. Split that line using "," into an array.

This way you will be able to read the content of your CSV file into your application.

Let me show a sample code as well.

FileReader fileReader = new FileReader(file)
BufferedReader br = new BufferedReader();

Map&lt;String, String[]&gt; lines = new HashMap&lt;String, String[]&gt;();
String line;
while ((line = br.readLine()) != null) {
    String[] lineContent= line.split(&quot;,&quot;);
    // use this in the way you need
    lines.put(lineContent[0], lineContent);
}

Now when you want to get the line having "LA1 ABC"; you just need to invoke lines.get(&quot;LA1 ABC&quot;).

答案2

得分: 0

你可以使用开源库来读取CSV文件。
OpenCSV就是这样一个库。

有一篇博文介绍了如何使用OpenCSV来读取CSV文件:
https://www.baeldung.com/opencsv

英文:

You can use open source libraries to read the CSV files.
OpenCSV is one such library.

One blog which explaing how to use OpenCSV to read the CSV
https://www.baeldung.com/opencsv

huangapple
  • 本文由 发表于 2020年10月25日 21:15:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/64524103.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定