【问题标题】:Arranging array of String from bytes [closed]从字节排列字符串数组[关闭]
【发布时间】:2018-05-21 17:53:18
【问题描述】:

我是 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;


    }

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

【问题讨论】:

    标签: java string file


    【解决方案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 的文件,其内容在原始帖子中描述,与方法本身位于磁盘上的同一位置。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多