CSV到字符串数组-JAVA
我有一个CSV文件,其中只有一列有100多行。我想把这些值放在一维数组中(只有在可能的情况下)。因此,它的工作原理与我手动编写字符串数组的工作原理相同。即CSV到字符串数组-JAVA,java,arrays,csv,Java,Arrays,Csv,我有一个CSV文件,其中只有一列有100多行。我想把这些值放在一维数组中(只有在可能的情况下)。因此,它的工作原理与我手动编写字符串数组的工作原理相同。即 String[] username = {'lalala', 'tatata', 'mamama'}; //<---if I did it manually String[] username = {after passing the CSV values}; //<---I want this like the above o
String[] username = {'lalala', 'tatata', 'mamama'}; //<---if I did it manually
String[] username = {after passing the CSV values}; //<---I want this like the above ones.
我知道我问了很多问题,但我非常感谢你的帮助。即使你看到这个问题,说这是废话。哦,还有一件事,我更希望它是JAVA。如果它只是一个csv,那么您可以使用带有适当正则表达式的字符串拆分方法。
请检查拆分方法您的问题的前半部分很简单,可以用多种不同的方法处理。就我个人而言,我会使用Scanner类并将分隔符设置为“,”。创建一个新的扫描仪对象,然后对其调用
setDelimiter(“,”
)。然后简单地扫描令牌。请参见上的示例。这种方法非常有效,因为它可以处理文件中的读取并根据您的条件(字符“,”分隔文件) 使用arraylist可能比使用数组更容易,因为您不必担心行数。数组具有无法更改的固定大小。i、 e ArrayList
由于您只有一列,因此无需担心csv中的逗号
示例代码如下所示:
import java.util.*;
import java.io.*;
public class MyClass {
private ArrayList<String> MyArray = new ArrayList<String>();
private Scanner scan;
public MyClass(){
try {
scan = new Scanner(new File("MyFile.csv"));
} catch (IOException ioex) {
System.out.println("File Not Found");
}
}
public ArrayList<String> getArray() {
while (scan.hasNext()) {
Scanner line = new Scanner(scan.nextLine());
MyArray.add(line.next());
}
return MyArray;
}
}
import java.util.*;
import java.io.*;
public class MyClass {
private ArrayList<String> MyArray = new ArrayList<String>();
private Scanner scan;
public MyClass(){
try {
scan = new Scanner(new File("MyFile.csv"));
} catch (IOException ioex) {
System.out.println("File Not Found");
}
}
public ArrayList<String> getArray() {
while (scan.hasNext()) {
Scanner line = new Scanner(scan.nextLine());
MyArray.add(line.next());
}
return MyArray;
}
}
MyClass f = new MyClass();
System.out.println(f.getArray());