Sprintf equivalent in Java

前端 未结 5 2048
小鲜肉
小鲜肉 2020-11-30 17:40

Printf got added to Java with the 1.5 release but I can\'t seem to find how to send the output to a string rather than a file (which is what sprintf does in C). Does anyone

5条回答
  •  [愿得一人]
    2020-11-30 18:20

    You can do a printf to anything that is an OutputStream with a PrintStream. Somehow like this, printing into a string stream:

    PrintStream ps = new PrintStream(baos);
    ps.printf("there is a %s from %d %s", "hello", 3, "friends");
    System.out.println(baos.toString());
    baos.reset(); //need reset to write new string
    ps.printf("there is a %s from %d %s", "flip", 5, "haters");
    System.out.println(baos.toString());
    baos.reset();
    

    The string stream can be created like this ByteArrayOutputStream:

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    

提交回复
热议问题