Java中的输入输出函数和IO流使用方法
Java是一门广受欢迎的编程语言,它提供了一些方便、易用的输入输出函数和IO流,方便开发者在Java程序中完成读写操作。
一、输入输出函数
1. System.out.println()
这是Java中最常用的一个输出函数,它可以输出字符串、整数、浮点数等各种类型的数据。例如:
System.out.println("Hello World!");
2. System.out.print()
该函数和System.out.println()函数类似,但它不会自动换行。例如:
System.out.print("Hello");
System.out.print("World");
输出的结果为:
HelloWorld
3. System.out.printf()
该函数可以用于格式化输出,可以指定输出的字符串格式。例如:
System.out.printf("My name is %s, age is %d", "John", 25);
输出的结果为:
My name is John, age is 25
二、IO流
Java中的IO流提供了许多用于读写文件和网络数据的类和接口。IO流分为字节流和字符流。
1. 字节流
字节流是一种以字节为单位进行读写的流,它可以读写任何类型的数据。Java中主要的字节流类有InputStream、OutputStream、FileInputStream、FileOutputStream等。
InputStream类和OutputStream类是抽象类,不能直接实例化,需要通过它们的子类进行实例化。例如:
InputStream input = new FileInputStream("myfile.txt");
OutputStream output = new FileOutputStream("myfile.txt");
FileInputStream和FileOutputStream类用于操作文件,它们可以读写文件中的数据。例如:
FileInputStream input = new FileInputStream("myfile.txt");
byte[] buffer = new byte[1024];
int len = input.read(buffer);
input.close();
FileOutputStream output = new FileOutputStream("myfile.txt");
output.write(buffer, 0, len);
output.close();
2. 字符流
字符流是一种以字符为单位进行读写的流,它可以读写纯文本数据。Java中主要的字符流类有Reader、Writer、FileReader、FileWriter等。
Reader类和Writer类是抽象类,不能直接实例化,需要通过它们的子类进行实例化。例如:
Reader reader = new FileReader("myfile.txt");
Writer writer = new FileWriter("myfile.txt");
FileReader和FileWriter类用于操作文件,它们可以读写文件中的字符。例如:
FileReader reader = new FileReader("myfile.txt");
char[] buffer = new char[1024];
int len = reader.read(buffer);
reader.close();
FileWriter writer = new FileWriter("myfile.txt");
writer.write(buffer, 0, len);
writer.close();
以上就是Java中输入输出函数和IO流的使用方法。在实际开发中,我们需要根据具体需求选择合适的输入输出方式,并进行相应的处理。
