System.out.printf(“%4d”) 在 BufferedWriter / FileWriter

System.out.printf(“%4d”) in BufferedWriter / FileWriter

我做了一个乘法table。问题是 table 没有按应有的顺序排序。

如果我只想将它打印在屏幕上,那么我会使用这个 System.out.printf(“%4d”)。我如何使用 BufferedWriter 解决这个问题?

而不是这个:

Irj be egy szamot:
5
1 2 3 4 5 
2 4 6 8 10 
3 6 9 12 15 
4 8 12 16 20 
5 10 15 20 25 `

我想要这个:

Irj be egy szamot: 
5
1  2  3  4  5 
2  4  6  8 10 
3  6  9 12 15 
4  8 12 16 20 
5 10 15 20 25 `

这是我的代码:

public class EgyszerEgy {
    public static void main(String[] args) {

        int a;
        int b;

        try {
            FileWriter writer = new FileWriter("EgyszerEgy.txt");
            BufferedWriter bf = new BufferedWriter(writer);

            Scanner tastatur = new Scanner(System.in);
            System.out.println("Irj be egy szamot: ");
            int szam = tastatur.nextInt();

            for (a = 1; a <= szam; ++a) {
                for (b = 1; b <= szam; ++b) {
                    int eredmeny = a * b;
                    String eredmenyString = String.valueOf(eredmeny);
                    bf.write(eredmenyString);
                    bf.write(" ");
                }
                bf.newLine();
            }
            bf.flush();
            bf.close();
        } catch (Exception e) {

        }

        // Kiolvasas
        //String result;
        try {
            FileReader fr = new FileReader("EgyszerEgy.txt");
            BufferedReader br = new BufferedReader(fr);
            String result;
            while ((result = br.readLine()) != null) {
                System.out.println(result);
            }
            br.close();
        } catch (Exception e) {

        }
    }
}

您可以创建与 printf 完全相同的格式,方法是使用 String.format 并将结果写入 BufferedWriter

您已经知道如何包装 FileWriter with a BufferedWriter. Now wrap it again with a PrintWriter, which has the printf() 方法。

您还应该使用 try-with-resources。它是在 Java 7 中添加的,所以绝对没有充分的理由不使用它,除非你卡在 Java 6 或更早的版本上。

同样适用于使用 NIO.2 API 而不是旧文件 I/O API。

Scanner tastatur = new Scanner(System.in);
System.out.println("Irj be egy szamot: ");
int szam = tastatur.nextInt();

try (PrintWriter fout = new PrintWriter(Files.newBufferedWriter(Paths.get("EgyszerEgy.txt")))) {
    for (int a = 1; a <= szam; ++a) {
        for (int b = 1; b <= szam; ++b) {
            int eredmeny = a * b;
            fout.printf("%3d ", eredmenyString);
        }
        fout.println();
    }
}