在 Java 中,您可以通过多种方式读取文件的内容,其中一种方法是使用 java.util.Scanner 类将其读取为字符串,为此,
示例
在系统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中从文件内容创建一个字符串?的详细内容,更多请关注编程之家其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。