所以我正在编写一个程序,它将读取一个csv文件并将文件的每一行放入一个数组中。我想知道是否可以命名在while循环中创建的单数数组。我也很想知道您是否对如何通过csv文件的列分隔行(包含csv文件的行)有任何想法。
这是我的代码:
package sample.package;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class SampleClass {
/**
* @param args
*/
public static String fileLocation; //Used to declare the file path
public static void readAndArray(String fileLocation) throws IOException { //Method to read a file and put each line into an array
BufferedReader lineRead = new BufferedReader(new FileReader(fileLocation)); //Read the file and be able to parse it into separate lines
String line = lineRead.readLine(); //Put line into variable so it isn't a boolean statement
while ((line = lineRead.readLine()) !=null) { //Make it possible to print out array as BufferedReader is used
String[] oneLine = new String[] {line}; //Put parsed line in new array and parsing that data for individual spots in array
System.out.println(oneLine[0]); //Print out each oneLine array
}
lineRead.close(); //Neatly close BufferedReader and FileReader
}
public static void main(String[] args) throws IOException{
readAndArray("filePath"); //Initialize method by inputting the file path
}
}
非常感谢你们!
答案 0 :(得分:0)
首先:欢迎使用stackoverflow!
如果不是这样,我假设您的问题与某种教育性编程任务有关:有许多处理CSV文件的库(具有其他功能,如读取标题行和按标题/列名读取行条目等)
但是...为什么编写CSV解析器应该是一个复杂的任务,我的意思是,它基本上只是用逗号分隔的值phhh!? >
长话短说:有RFC 4180,但不要指望您所有的.csv
文件都坚持下去。引用Wikipedia:
CSV文件格式未完全标准化。基本思想 用逗号分隔字段很明显,但是这个想法得到了 当字段数据还可能包含逗号甚至是 嵌入式换行符。 CSV实现可能无法处理此类字段 数据,也可以使用引号将其括起来。报价单 不能解决所有问题:某些字段可能需要嵌入引号 标记,因此CSV实现可能包含转义字符或转义 序列。
在意识到并希望理解所提供的兼容性警告之后,下面的代码示例将完全忽略它,并提供了一种快速而肮脏的解决方案(请不要在生产中使用它,认真地……如何不被解雇101:使用经过良好测试的库,例如opencsv或Apache Commons CSV):
public static void main(String[] args)
{
Path path = Paths.get("some path"); // TODO Change to path to an CSV file
try (Stream<String> lines = Files.lines(path))
{
List<List<String>> rows = lines
// Map each line of the file to its fields (String[])
.map(line -> line.split(","))
// Map the fields of each line to unmodifiable lists
.map(fields -> Collections.unmodifiableList(Arrays.asList(fields))
// Collect the unmodifiable lists in an unmodiable list (listception)
.collect(Collectors.toUnmodifiableList());
// Ensure file is not empty.
if (rows.isEmpty())
{
throw new IllegalStateException("empty file");
}
// Ensure all lines have the same number of fields.
int fieldsPerRow = rows.get(0).size();
if (!rows.stream().allMatch(row -> row.size() == fieldsPerRow))
{
throw new IllegalStateException("not all rows have the same number of fields");
}
// Assume the file has a header line appearing as the first line.
System.out.printf("Column names: %s\n", rows.get(0));
// Read the data rows.
rows.stream()
.skip(1) // Skip header line
.forEach(System.out::println);
}
catch (IOException | UncheckedIOException e)
{
e.printStackTrace(); // TODO Handle exception
}
}
此代码假定:
快速又肮脏...违反了RFC;)