从文本文件读取并存储在字符串中 [英] Reading from a text file and storing in a String

查看:113
本文介绍了从文本文件读取并存储在字符串中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们怎样才能从一个字符串变量一个文本文件,存储读取数据?

How can we read data from a text file and store in a String variable?

是可以传递文件名的方法,它会返回字符串这是来自文件的文本。

is it possible to pass the filename in a method and it would return the String which is the text from the file.

我必须导入什么样的工具? 。声明的清单将是巨大的。

What kind of utilities do I have to import? A list of statements will be great.

推荐答案

这是necersary进口:

These are the necersary imports:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;



这是将允许从一个文件通过它传递的文件名作为读取的方法参数是这样的: READFILE( yourFile.txt);

String readFile(String fileName) throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(fileName));
    try {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            sb.append(line);
            sb.append("\n");
            line = br.readLine();
        }
        return sb.toString();
    } finally {
        br.close();
    }
}

这篇关于从文本文件读取并存储在字符串中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆