Java 中读取字符串318


在 Java 中,有许多方法可以读取字符串。字符串是不可变的字符序列,这意味着一旦创建,就不能更改其内容。但是,可以使用 String 类中的方法来操纵字符串。

从控制台读取字符串

要从控制台读取字符串,可以使用 Scanner 类。Scanner 类有一个 next() 方法,它返回控制台输入的下一个字符串。
import ;
public class ReadString {
public static void main(String[] args) {
Scanner scanner = new Scanner();
// 从控制台读取字符串
String input = ();
// 打印输入的字符串
("输入的字符串:" + input);
}
}

从文件中读取字符串

要从文件中读取字符串,可以使用 File 类和 Scanner 类。File 类有一个 newScanner() 方法,它返回一个 Scanner 对象,该对象可以用来从文件读取数据。
import ;
import ;
public class ReadStringFromFile {
public static void main(String[] args) {
try {
// 创建 File 对象
File file = new File("");
// 创建 Scanner 对象
Scanner scanner = new Scanner(file);
// 从文件中读取字符串
String input = ();
// 打印输入的字符串
("从文件中读取的字符串:" + input);
} catch (FileNotFoundException e) {
();
}
}
}

从网络读取字符串

要从网络读取字符串,可以使用 URL 类和 Scanner 类。URL 类有一个 openStream() 方法,它返回一个 InputStream 对象,该对象可以用来从 URL 读取数据。
import ;
import ;
import ;
public class ReadStringFromURL {
public static void main(String[] args) {
try {
// 创建 URL 对象
URL url = new URL("");
// 打开 InputStream
InputStream inputStream = ();
// 创建 Scanner 对象
Scanner scanner = new Scanner(inputStream);
// 从网络读取字符串
String input = ();
// 打印输入的字符串
("从网络读取的字符串:" + input);
} catch (IOException e) {
();
}
}
}


在 Java 中,有许多方法可以读取字符串。根据需要读取的字符串的来源,可以使用 Scanner 类、File 类、URL 类或其他方法。

2024-10-15


上一篇:Java 数组去重的全面指南

下一篇:Java 中的基本数据类型