java从文件读取数据_如何使用Java从文件读取数据到String?

在Java中,您可以通过几种方式读取文件的内容,一种方式是使用java.util.Scanner类将其读取为字符串,为此,实例化 Scanner 类,将要读取的文件的路径作为其构造函数的参数。

创建一个空的字符串缓冲区。

如果 Scanner 有下一行,即hasNextLine()。则启动带有条件的while循环。

在循环中,使用append()方法将文件的每一行附加到StringBuffer对象。

使用toString()方法将缓冲区内容转换为String 。

在系统的C目录中创建一个名为sample.txt的文件,然后将以下内容复制并粘贴到其中。nhooo.com 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

nhooo.com, you can learn at your own pace, in your own space.

After a successful journey of providing the best learning content at

nhooo.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: nhooo.com 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 nhooo.com, you can

learn at your own pace, in your own space. After a successful journey of providing the best learning content

at nhooo.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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值