Java 如何输入内容
在Java中,我们可以使用不同的方法来输入内容,包括从键盘输入、从文件读取和从网络获取等。下面将介绍一些常用的方法和示例。
1. 从键盘输入
使用Scanner类
import java.util.Scanner;
public class KeyboardInputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一个整数:");
int num = scanner.nextInt();
System.out.println("您输入的整数是:" + num);
System.out.print("请输入一个字符串:");
String str = scanner.next();
System.out.println("您输入的字符串是:" + str);
scanner.close();
}
}
上述代码使用了Java标准库中的Scanner类来实现从键盘输入。首先创建一个Scanner对象,然后使用nextInt()
方法读取整数,使用next()
方法读取字符串。最后使用close()
方法关闭Scanner对象。
使用BufferedReader类
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class KeyboardInputExample {
public static void main(String[] args) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.print("请输入一个整数:");
int num = Integer.parseInt(reader.readLine());
System.out.println("您输入的整数是:" + num);
System.out.print("请输入一个字符串:");
String str = reader.readLine();
System.out.println("您输入的字符串是:" + str);
} catch (IOException e) {
e.printStackTrace();
}
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
上述代码使用了Java标准库中的BufferedReader类来实现从键盘输入。首先创建一个BufferedReader对象,通过InputStreamReader将System.in转换为字符流。然后使用readLine()
方法读取输入的整数和字符串。最后使用close()
方法关闭BufferedReader对象。
2. 从文件读取
使用FileInputStream类
import java.io.FileInputStream;
import java.io.IOException;
public class FileInputExample {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("input.txt");
int data;
while ((data = fis.read()) != -1) {
System.out.print((char) data);
}
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
上述代码使用了Java标准库中的FileInputStream类来实现从文件读取。首先创建一个FileInputStream对象,传入文件名作为参数。然后使用read()
方法读取文件中的数据,直到读取到文件末尾(返回-1)。最后使用close()
方法关闭FileInputStream对象。
3. 从网络获取
使用URLConnection类
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class NetworkInputExample {
public static void main(String[] args) {
try {
URL url = new URL("
URLConnection connection = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
上述代码使用了Java标准库中的URLConnection类来实现从网络获取数据。首先创建一个URL对象,传入URL地址作为参数。然后使用openConnection()
方法打开一个连接,并通过getInputStream()
方法获取输入流。接着使用BufferedReader类读取输入流中的数据,直到读取到末尾(返回null)。最后使用close()
方法关闭输入流。
以上是一些常见的Java输入内容的方法和示例,根据不同的需求可以选择合适的方法来实现输入。希望对你有所帮助!