Joe*_*Joe 0 java csv arrays line separator
我有一个类从文件中读取特定列并将其插入到数组中。我想将该数组用逗号分隔符打印在同一行上。
下面是我的代码:
public static void getArray(int Column, File path, String Splitter) throws IOException
{
List<String> lines = Files.readAllLines(path.toPath(), StandardCharsets.US_ASCII);
for (String line : lines)
{
String[] array = line.split(Splitter);
//Will return all elemetns on the same line but without any separation, i need some kind of separation
// if i use System.out.print(array[Column]+" ,");
// i will always get a , at the end of the line
System.out.print(array[Column]);
}
}
getArray(3, file, "|");
Run Code Online (Sandbox Code Playgroud)
当前输出为:
abcdefg
期望的输出是:
a,b,c,d,e,g
您可以使用joining
收集器。
用分隔符连接数组元素,
。
String result = Arrays.stream(array)
.collect(Collectors.joining(","));
Run Code Online (Sandbox Code Playgroud)
将数组中给定元素的字符与分隔符连接起来,
。
String result = Arrays.stream(array[Column].split(""))
.collect(Collectors.joining(","));
Run Code Online (Sandbox Code Playgroud)
使用分隔符连接数组中给定元素的字符的另一种变体,
:
String result = array[Column].chars()
.mapToObj( i -> String.valueOf((char)i))
.collect(Collectors.joining(","));
Run Code Online (Sandbox Code Playgroud)