gpt4 book ai didi

java - 将字符串写入文件中的特定位置

转载 作者:行者123 更新时间:2023-12-01 08:12:51 24 4
gpt4 key购买 nike

我正在使用 BufferedWriter 将字符串写入文件,如下所示:

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class Test {

public static void main(String[] args) throws IOException {
String myname = "JOHN DOE MAXWELL";
String myotherName = "MELCHIZEDEK NEBUCHARDINEZZAR";
String mylocation = "SOUTH EAST";
String myotherlocation = "SOUTH WEST";
File f = new File("MyFile.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(f));
bw.write(myname + " " + mylocation);
bw.newLine();
bw.write(myothername + " " + myotherlocation);
bw.close();
}
}

我需要编写mylocation,这样无论字符串myname的长度如何,mylocation的开始位置都不会受到影响。请帮忙。

我的输出应该是:

JOHN DOE MAXWELL          SOUTH EAST
MELCHIZEDEK NEBUCHARDI SOUTH WEST

最佳答案

你可以做

bw.write(String.format("%-20s%s%n", myName, myLocation));

您可以使用 PrintWriter 来使用 printf(),这两者都可以。

例如使用PrintWriter

pw.printf("%-" + myNameWidth + "s%s%n", myName, myLocation);

关于java - 将字符串写入文件中的特定位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15949737/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com