在 Windows 中使用窗口流数据使用“:”时无法写入文件

问题描述 投票:0回答:1

我在运行 Java ApacheBeam 代码时遇到问题。当尝试在我的 Windows 系统上创建名称中带有冒号的文件时,程序会抛出错误,指出文件名无效。

我知道该错误是由于我的 windowingTimestamp 造成的,其中它在时间戳中包含 : 作为文件名。

我一直在转换时间戳值,我不想有基本的默认文件名。

实际文件名:output2020-12-12T15:00:10.000Z-2020-12-12T15:00:15.000Z-pane-0-last-00000-of-00001

预期文件名:output2020-12-12T15.00.10.000Z-2020-12-12T15.00.15.000Z-pane-0-last-00000-of-00001

output.apply(ParDo.of(new DoFn<KV<String,Long>,String> (){

     @ProcessElement
    public void processElement(ProcessContext c, BoundedWindow window){

        /*In Terminal Results
        System.out.println(String.format(
                "%s: %s %s", window.maxTimestamp(), c.element(). getKey(),c.element().getValue()));

         */
         c.output(String.format("%s %s %s",window.maxTimestamp(), Objects.requireNonNull(c.element()).getKey(), Objects.requireNonNull(c.element()).getValue()));

    }
})).apply(TextIO.write().to("src/main/resources/Sink/FixedWindow/output").withWindowedWrites().withNumShards(1));
java timestamp apache-beam apache-beam-io windowing
1个回答
0
投票

要在 Apache Beam 中实现预期的文件名格式,您可以将时间戳转换为特定格式的字符串,然后将其用作文件名的一部分。您可以使用 Java 中的 DateTimeFormatter 根据需要格式化时间戳字符串。您可以通过以下方式修改代码来实现此目的:

import java.time.format.DateTimeFormatter;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.values.KV;
import org.apache.beam.sdk.transforms.windowing.BoundedWindow;
import org.apache.beam.sdk.io.TextIO;

public class YourDoFn extends DoFn<KV<String, Long>, String> {

  private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH.mm.ss.SSS'Z'");

  @ProcessElement
  public void processElement(ProcessContext c, BoundedWindow window) {
      String timestamp = window.maxTimestamp().format(formatter); // Format the timestamp
      String fileName = String.format("output%s-pane-0-last-00000-of-00001", timestamp);
      c.output(fileName);
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.