Reading text file into a char array in Java(将文本文件读入Java中的char数组)
问题描述
我正在读取一个文本文件并尝试将它逐个字符地存储到一个数组中.我的方法(如下)预先定义了一个初始长度为 100000 的 char
数组(我的主要问题在这里).因此,如果文件包含的字符少于该数量(如果字符多于该数量,也会出现问题),那么我的数组中有空值.我想避免这种情况.有没有办法预先确定文本文件中存在的字符数量?还是有更好的方法来按字符存储文件?
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
}
推荐答案
使用 ArrayList of Characters 来接受值.之后将 ArrayList 转换为 Array 为
Use an ArrayList of Characters to accept the values. After that convert ArrayList to an Array as
char[] resultArray = list.toArray(new char[list.size()]);
您应该使用 br.readLine() 而不是 br.read(),如下所示:
You should use br.readLine() instead of br.read() as follows:
String str;
while((str = br.readLine())!=null){
str.tocharArray();
}
这篇关于将文本文件读入Java中的char数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将文本文件读入Java中的char数组


基础教程推荐
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01