读文本文件转换成Java中的一个字符数组 [英] Reading text file into a char array in Java

查看:206
本文介绍了读文本文件转换成Java中的一个字符数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读的文本文件,并试图将其存储到由字符数组字符。我的方法(下)pre-定义了10万的初始长度(我的主要问题在这里)在字符阵列。所以,如果该文件包含小于量字符(问题也若比这更多个字符),则有在我的数组空值。我想避免这种情况。有没有一种方法,以predetermine字符present在文本文件中的金额是多少?还是有更好的方法完全存储由字符文件的字符?

 字符BUF [] =新的char [100000]。
FR的FileReader =新的FileReader(文件名);
BR的BufferedReader =新的BufferedReader(FR);
br.read(BUF);
的for(int i = 0; I< buf.length;我++)
{
     //这里做的东西
}


解决方案

使用字符的ArrayList的接受值。在这之后的ArrayList转换到数组为

 的char [] = resultArray list.toArray(新的char [则为list.size()]);

您应该使用br.readLine代替br.read如下,

 字符串str;
而((海峡= br.readLine())!= NULL){
        str.tocharArray();
}

I am reading a text file and trying to store it into an array char by char. My approach (below) pre-defines a char array with an initial length of 100000 (my main issue here). So, if the file contains characters less than that amount (problem also if more characters than that), then there are nulls in my array. I want to avoid that. Is there a way to predetermine the amount of characters present in a text file? Or is there a better approach altogether to store the file char by char?

char buf[] = new char[100000];
FileReader fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
br.read(buf);
for(int i = 0; i < buf.length; i++)
{
     //Do stuff here
}

解决方案

Use a ArrayList of Characters to accept the values. After that convert ArrayList to an Array as

 char[] resultArray = list.toArray(new char[list.size()]);

You should use br.readLine instead of br.read as follows,

String str;
while((str = br.readLine())!=null){
        str.tocharArray();
}

这篇关于读文本文件转换成Java中的一个字符数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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