IO

主要使用:文件读写

文件读:FileUtils.readLines
文件写:FileUtils.writeLines

下面是一个实际的例子,一共涉及三个文件:

  1. 文件1:cer-userid-technicianid.txt 所有认证技师的userId,technicianId 数据格式,第一列userId,第二列technicianId,tab键隔开

    178479650 2134
    666951 193
    51265592 1461
    145921104 76290
    720872160 2438

  2. 文件2:technicianid-yuan.txt 所有报名参加活动的technicianId 数据格式,只有一行,逗号分隔

    1348,95239,95243,95244,95245,95246,95248

  3. 文件3:UserId-TechnicianId-result.txt 输出的结果文件,求所有报名参加活动的技师中已认证技师的userId,technicianId。

代码如下:

@Test
public void test32() throws IOException {
    final List<String> lines = FileUtils.readLines(new File("/Users/chenjp/Documents/learn/work/file/cer-userid-technicianid.txt"), "utf-8");

    final List<String> technicianIdList = FileUtils.readLines(new File("/Users/chenjp/Documents/learn/work/file/technicianid-yuan.txt"), "utf-8");

    final File result = new File("/Users/chenjp/Documents/learn/work/file/UserId-TechnicianId-result.txt");

    final ArrayList<Integer> technicianIds = Lists.newArrayList(FluentIterable.from(Splitter.on(",").omitEmptyStrings().splitToList(technicianIdList.get(0))).transform(new Function<String, Integer>() {
        @Override
        public Integer apply(String input) {
            return NumberUtils.toInt(input);
        }
    }));

    Lists.newArrayList(FluentIterable.from(lines).transform(new Function<String, String>() {
        @Override
        public String apply(String input) {
            try {
                if (StringUtils.isBlank(input)) {
                    return null;
                }
                List<String> list = Splitter.onPattern("\\s").omitEmptyStrings().splitToList(input);
                if (!technicianIds.contains(NumberUtils.toInt(list.get(1)))) {
                    System.err.println(String.format("bad technicianId[%s]", list.get(1)));
                    return null;
                }
                System.out.println(String.format("write to result file[%s]", input));
                FileUtils.writeLines(result, "utf-8", Lists.newArrayList(input), true);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return input;
        }
    }));
}

结果自体会

results matching ""

    No results matching ""