【问题标题】:Java - Apache Beam: Read file from GCS with "UCS2-LE BOM" encodingJava - Apache Beam:使用“UCS2-LE BOM”编码从 GCS 读取文件
【发布时间】:2020-03-05 16:22:30
【问题描述】:

我想使用 TextIO 读取 UCS2-LE BOM 中的文件,但它似乎不起作用。 有没有办法使用这种编码的 TextIO ?或者是否有其他库可以很好地处理这种类型的编码?

我的代码是 JAVA (Apache Beam)

PCollection<KV<String, String>> csvElements =
            pipeline.apply("Reads the input csv file", TextIO
                    .read()
                    .from(options.getPolledFile()))
                    .apply("Read File", ParDo.of(new DoFn<String, KV<String,String>>(){
                        @ProcessElement
                        public void processElement(ProcessContext c) throws UnsupportedEncodingException {
                            String element = c.element();

                            String elStr = new String(element.getBytes(),"UTF-16LE");
                            c.output(elStr);}}));

【问题讨论】:

  • 嗨@Oumab10!请问你能分享错误信息吗?我没有发现这件事有任何限制
  • @MethkalKhalawi 我没有收到错误,但是当我打印元素时,编码不正确,我得到了奇怪的字符。

标签: java encoding google-cloud-platform google-cloud-dataflow apache-beam


【解决方案1】:

我在中等帖子中找到了解决方案:Solution

我正在读取的文件存储在 GCS 中,因此在 try 部分中添加了行(与原始代码相比。)

file = "path to gas file";    
PCollection<String> readCollection = pipeline.apply(FileIO.match().filepattern(file))
                    .apply(FileIO.readMatches())
                    .apply(FlatMapElements
                            .into(strings())
                            .via((FileIO.ReadableFile f) -> {
                                List<String> result = new ArrayList<>();
                                try {
                                    ReadableByteChannel byteChannelParse = f.open();
                                    InputStream inputStream = Channels.newInputStream(byteChannelParse);
                                    BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "UTF-16"));
                                    String line = br.readLine();
                                    while (line != null) {
                                        result.add(line);
                                        line = br.readLine();
                                    }
                                    br.close();
                                    inputStream.close();
                                }

                                catch (IOException e) {
                                    throw new RuntimeException("Error while reading", e);
                                }
                                return result;
                            }));

PS:我没有添加带有凭据的行,因为我将它传递给了 IntelliJ 参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-23
    • 2020-01-09
    • 2020-01-15
    • 2019-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多