Java中的基础输入输出函数的使用
Java中的基础输入输出函数主要包括使用控制台和文件进行输入输出的函数。
首先,Java提供了控制台输入的函数System.in。我们可以使用Scanner类来读取控制台输入的数据。首先需要导入Scanner类:import java.util.Scanner;,然后创建Scanner对象来读取输入数据:Scanner scanner = new Scanner(System.in);,接着可以使用scanner对象的方法来获取输入数据,比如使用next()方法来读取下一个单词或字符串,使用nextInt()方法来读取下一个整数,使用nextLine()方法来读取整行数据等。例如,
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 读取下一个字符串
String str = scanner.next();
System.out.println("输入的字符串为:" + str);
// 读取下一个整数
int num = scanner.nextInt();
System.out.println("输入的整数为:" + num);
// 读取下一行数据
String line = scanner.nextLine();
System.out.println("输入的整行数据为:" + line);
}
}
除了控制台输入外,Java还提供了文件输入输出的函数来读写文件。我们可以使用FileInputStream和FileOutputStream类来进行文件输入输出操作。首先需要导入相关类:import java.io.FileInputStream; import java.io.FileOutputStream;,然后可以创建FileInputStream对象来读取文件内容,创建FileOutputStream对象来写入文件内容。例如,
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("input.txt");
FileOutputStream fos = new FileOutputStream("output.txt");
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) != -1) {
fos.write(buffer, 0, length);
}
fis.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
以上代码将会把input.txt文件中的内容复制到output.txt文件中。
除了使用FileInputStream和FileOutputStream进行文件输入输出外,Java还提供了BufferedReader和BufferedWriter类来读写文件。这两个类可以提供缓冲功能,提高文件读写的效率。例如,
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"));
String line;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
}
reader.close();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
以上代码将会把input.txt文件中的内容复制到output.txt文件中,每行内容之间添加一个换行符。
在Java中,还可以使用System.out库提供的print和println函数来输出结果到控制台。print函数不会换行,而println函数会在输出结果后换行。例如,
public class Main {
public static void main(String[] args) {
int num1 = 10;
int num2 = 20;
System.out.println("num1的值为:" + num1);
System.out.println("num2的值为:" + num2);
}
}
以上代码会输出:
num1的值为:10 num2的值为:20
