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

问题描述 投票:0回答:2

我做了一个乘法表。问题在于该表未按应有的顺序排序。

如果只想在屏幕上打印,则使用此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) {

        }
    }
}
java filewriter bufferedwriter
2个回答
2
投票

您已经知道如何用FileWriter包装FileWriter。现在,再次使用具有BufferedWriter方法的BufferedWriter对其进行包装。

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

与使用NIO.2 API代替旧的File I / O API相同。

PrintWriter

1
投票

您可以使用PrintWriter创建与printf()完全相同的格式,并将结果写入printf()

© www.soinside.com 2019 - 2024. All rights reserved.