字符串格式化文件

时间:2015-11-15 00:48:42

标签: java file formatting

我正在尝试在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();
        }
    }
}

2 个答案:

答案 0 :(得分:2)

首先,我会使用Scannertry-with-resources close。而且,我会使用String.split(String)来解析该行。然后,您的格式String需要{{1>}(减号 width 之前)左对齐。像,

-

我使用您提供的文件运行,并获得(请求的)

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 :(得分:0)

你需要在printf中ffmpeg -loop 1 -i image.jpg -i video.mp4 -filter_complex "overlay=(W-w)/2:(H-h)/2:shortest=1,format=yuv420p" -c:a copy output.mp4 使其左对齐。

例:
%-70s
以上将打印'Hi'

printf("'%5s'", "Hi");
以上将打印'Hi'