Write

Nannan Lv5

Write

1.BufferedWriter

主要用于写入字符串,如果要将整型写入到BufferedWriter,你需要先转为字符串再进行写入。如果你尝试传递一个整数,它将被视为字符的Unicode码。

头文件:

1
import java.io.*;

样例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import java.io.*;

public class Main {
public static void main(String[] args) throws Exception{
BufferedWriter cout = new BufferedWriter(new OutputStreamWriter(System.out));

//输出字符串(不会自动换行)
String s = "abcdef";
cout.write(s+"\n");
//输出int
int a = 12345;
cout.write(a+"\n");//字符串连接操作符 + 会自动调用对象的 toString 方法,将其转换为字符串
int b = 65;
cout.write(Integer.toString(a));//手动转为字符串再输出
//输出小数
double d = 12.345;
cout.write(d+"\n");
cout.flush();//使用完毕,一定要在末尾添加!!
}
}

2.PrintWriter

PrintWriter 提供了更多方便的方法,用于输出各种数据类型,包括基本类型和对象。它还提供自动刷新的功能,当调用 println 方法时,会自动调用 flush 方法。

BufferedWriter 的区别:

BufferedWriter 主要提供了对底层 Writer 的缓冲,以提高写入性能。它没有像 PrintWriter 那样提供专门的方法用于输出各种数据类型,而是使用 write 方法将数据以字符串形式写入。

性能方面:由于 PrintWriter 提供了更多高级功能,可能在性能上略逊于 BufferedWriter,尤其是在大量数据写入时。BufferedWriter 的主要目的是通过缓冲提高性能。

使用场景:

  • 如果你需要方便地输出各种数据类型,并且希望有自动刷新的功能,可以选择 PrintWriter
  • 如果你主要关注性能,需要对输出进行缓冲,但不需要额外的高级功能,可以选择 BufferedWriter

头文件:

1
import java.io.*;

样例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.io.*;

class Main {

public static void main(String[] args) throws Exception {
PrintWriter cout = new PrintWriter(new OutputStreamWriter(System.out));
//输出整数
cout.print(114514+"\n");
cout.println(151);
//输出小数
cout.println(1145.14);
cout.print(String.format("%.5f\n", 114514.55));

//输出字符串
cout.print("hello world\n");
cout.close();
}
}

3.String.format

头文件:

1
import java.io.*;

样例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import java.io.*;

public class Main {
public static void main(String[] args) throws Exception{
BufferedWriter cout = new BufferedWriter(new OutputStreamWriter(System.out));
String s = String.format("%-18d\n",123456789101112L);//总宽带为18+左对齐+行末换行
cout.write(s);
String s2 = String.format("%18d\n",123456789101112L);//总宽带为18+右对齐+行末换行
cout.write(s2);
String s3 = String.format("%.5f\n",1234567891011.12);
cout.write(s3);
cout.flush();
}
}
  • Title: Write
  • Author: Nannan
  • Created at : 2024-03-11 18:38:00
  • Updated at : 2024-09-30 21:03:21
  • Link: https://redefine.ohevan.com/2024/03/11/二、write/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments