gpt4 book ai didi

java - 文件中的字符串格式

转载 作者:行者123 更新时间:2023-11-30 03:10:32 24 4
gpt4 key购买 nike

我正在尝试用 java 格式化文件。我正在读取一个文件,以逗号分隔并尝试将其转换为柱状形式。有什么建议我可以解决这个问题吗?文本文件包含:

1, Short line, A, 14323, Hello
4, A litter longer, L, 455, Alright
6, Another line that that is a a little longer, X, 4432, TT
10, This is the biggggggggggggggggggggggggggggggest line, T, 543, OKOKOK

我试图让它看起来像这样:

1.  Short line                                               A         14323       Hello
4. A litter longer L 455 Alright
6. Another line that that is a a little longer X 4432 TT
10. This is the biggggggggggggggggggggggggggggggest line T 543 OKOKOK

我的输出如下所示:

1.                                            Short line       A     14323  Hello 
4. A litter longer L 455 Alright
6. Another line that that is a a little longer X 4432 TT
10. This is the biggggggggggggggggggggggggggggggest line T 543 OKOKOK

这是迄今为止我的代码:

import java.io.*;
public class trash {

public static void main(String[] args) {
try {
FileReader f = new FileReader("Question.txt");
BufferedReader b = new BufferedReader(f);
String read = b.readLine();
while (read != null) {
int index = read.indexOf(",");
String newStringRead = read.substring(index+1);
String sub = read.substring(0,index+1);
sub = sub.replace(",",".");
newStringRead = newStringRead.replace((read.substring(0,index+1))," \t");
newStringRead = newStringRead.replace(",", "\t");
System.out.printf("%2s %70s %n",sub,newStringRead);
read = b.readLine();
}
b.close();
} catch (FileNotFoundException e) {
System.out.println("cant find file");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

最佳答案

首先,我会使用 Scanner和一个try-with-resources close 。而且,我会使用 String.split(String)来解析该行。那么你的格式String需要一个-(减号宽度之前)来左对齐。比如,

try (Scanner scanner = new Scanner(new File(
System.getProperty("user.home"), "Desktop/stackQuestion.txt"))) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] arr = line.split(",\\s*");
System.out.printf("%-3s %-56s %-9s %-11s %s%n", arr[0] + ".",
arr[1], arr[2], arr[3], arr[4]);
}
} catch (FileNotFoundException e) {
System.out.println("cant find file");
} catch (IOException ex) {
ex.printStackTrace();
}

我用你提供的文件运行,并得到了(所请求的)

1.  Short line                                               A         14323       Hello
4. A litter longer L 455 Alright
6. Another line that that is a a little longer X 4432 TT
10. This is the biggggggggggggggggggggggggggggggest line T 543 OKOKOK

关于java - 文件中的字符串格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33715163/

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