从字节排列String数组

时间:2018-05-21 17:53:18

标签: java string file

我是java新手并试图处理一些逻辑。我有档案

5049,INF
5049,INF
5049,INF
5049,INF
5049,INF
5051,INF
5051,INF
5051,BNF
5051,TNF

我需要像

这样的字符串连接中的这个文件数据

pIntString值为5049,5051,pString值为INF,BNF,TNF。

我的Java代码

    Path path = Paths.get(fileName);
    byte[] data = Files.readAllBytes(path);

    String str = new String(data);
    //System.out.println(data.toString());
    String[] strValue = str.split(",");
    String pushidString = null;
    String pIntString = strValue[0];

    for (int i=0;i<strValue.length-2;i++) {

        pushidString = strValue[i+2];
        pIntString = pushidString + pIntString;


    }

但是这段代码缺乏基本逻辑。任何帮助将不胜感激

1 个答案:

答案 0 :(得分:1)

我认为此代码涵盖了您所要求的内容:

  • 一次读取一个文件的行
  • 跟踪List数据结构中列的值
  • 循环显示列并输出以逗号分隔的值

代码:

public void showFileContents() throws Exception {
    Path path = Paths.get(this.getClass().getResource("bar.txt").getPath());

    // read each line one at a time
    List<String> lines = Files.readAllLines(path);

    List<String> firstColumn = new ArrayList<>();
    List<String> secondColumn = new ArrayList<>();

    // Loop through each line and do whatever you want with them
    for (String line : lines) {
        String[] strValue = line.split(",");
        firstColumn.add(strValue[0]);
        secondColumn.add(strValue[1]);
    }

    // Looks like you wanted them separated by columns in one String, so that looks like:
    System.out.println("Values from first column:");
    System.out.println(String.join(",", firstColumn));
    System.out.println("Values from second column:");
    System.out.println(String.join(",", secondColumn));
}

此测试类使用名为bar.txt的文件,其中包含原始帖子中描述的内容,位于磁盘上与方法本身相同的位置。