在 Java 中,如何根据文件内容创建字符串?
javaobject oriented programmingprogramming更新于 2024/2/11 2:20:17
在 Java 中,您可以通过多种方式读取文件内容,其中一种方法是使用 java.util.Scanner 类将其读入字符串,为此,
实例化 Scanner 类,并将要读取的文件的路径作为其构造函数的参数。
创建一个空的字符串缓冲区。
如果 Scanner 有下一行,则启动一个带有条件的 while 循环。即在while中hasNextLine()。
在循环中使用append()方法将文件的每一行附加到StringBuffer对象。
使用toString()方法将缓冲区的内容转换为字符串。
示例
在系统的C目录中创建一个名为sample.txt的文件,将以下内容复制并粘贴到其中。
Tutorials Point is an E-learning company that set out on its journey to provide knowledge to that class of readers that responds better to online content. With Tutorials Point, you can learn at your own pace, in your own space. After a successful journey of providing the best learning content at tutorialspoint.com, we created our subscription based premium product called Tutorix to provide Simply Easy Learning in the best personalized way for K-12 students, and aspirants of competitive exams like IIT/JEE and NEET.
以下 Java 程序将文件 sample.txt 的内容读入字符串并打印。
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class FileToString {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(new File("E://test//sample.txt"));
String input;
StringBuffer sb = new StringBuffer();
while (sc.hasNextLine()) {
input = sc.nextLine();
sb.append(" "+input);
}
System.out.println("Contents of the file are: "+sb.toString());
}
}
输出
Contents of the file are: Tutorials Point is an E-learning company that set out on its journey to provide knowledge to that class of readers that responds better to online content. With Tutorials Point, you can learn at your own pace, in your own space. After a successful journey of providing the best learning content at tutorialspoint.com, we created our subscription based premium product called Tutorix to provide Simply Easy Learning in the best personalized way for K-12 students, and aspirants of competitive exams like IIT/JEE and NEET.
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

