如何在java中将文件读入字符串? [英] How to read a file into string in java?

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

问题描述

我已将文件读入String。该文件包含各种名称,每行一个名称。现在的问题是我想在String数组中使用这些名称。

I have read a file into a String. The file contains various names, one name per line. Now the problem is that I want those names in a String array.

为此,我编写了以下代码:

For that I have written the following code:

String [] names = fileString.split("\n"); // fileString is the string representation of the file

但是我没有得到想要的结果和数组分割字符串后得到的长度为1.这意味着fileString没有\ n字符,但文件中有\\ n字符。

But I am not getting the desired results and the array obtained after splitting the string is of length 1. It means that the "fileString" doesn't have "\n" character but the file has this "\n" character.

那么如何解决这个问题?

So How to get around this problem?

推荐答案

问题不在于如何分割字符串;该位是正确的。

The problem is not with how you're splitting the string; that bit is correct.

您必须检查如何将文件读取到字符串。你需要这样的东西:

You have to review how you are reading the file to the string. You need something like this:

private String readFileAsString(String filePath) throws IOException {
        StringBuffer fileData = new StringBuffer();
        BufferedReader reader = new BufferedReader(
                new FileReader(filePath));
        char[] buf = new char[1024];
        int numRead=0;
        while((numRead=reader.read(buf)) != -1){
            String readData = String.valueOf(buf, 0, numRead);
            fileData.append(readData);
        }
        reader.close();
        return fileData.toString();
    }

这篇关于如何在java中将文件读入字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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