java 用readline读取txt文件内的一段文章,如何让读取的内容转为一维数组。

文件内容比如是这样
hello java
have a good day
想让内容不换行。

Java使用readline读取txt文件内的一段文章,将读取的内容转为一维数组,可以实现知道文件含有的字符串个数,创建一个字符串数组,然后每读取一个字符,就放到数组中,如下代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileReader;
class Demo
{
public static void main(String[] args) throws IOException
{
int n=10;//数组长度
int count=0;//计数器
int ch=0;//用于接收读取的字符
//创建高效字符输入流对象
BufferedReader br=new BufferedReader(new FileReader("abc.txt"));

char[] chs=new char[n];
//将abc.txt文件中前10个字符写入数组
while((ch=br.read())!=-1)
{
if(count==n-1)
{
break;
}
else
{
chs[count]=(char)ch;
count++;
}
}
//打印数组
for(int x=0;x<chs.length;x++)
{
System.out.print(chs[x]);
}
}
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2016-05-11
File f = new File("你的文件");
InputStream input = new FileInputStream(f);

BufferedReader b = new BufferedReader(new InputStreamReader(input));
List<String> resultList = new ArrayList<>();
String value = b.readLine();
if(value != null){
resultList.add(value);
while(value !=null){
 value = b.readLine();
 resultList.add(value);
}
}
b.close;
input.close;

这样就把读取的行内容存储到list中了。它和一维数组是一样的。也可以用

List<String> list = new ArrayList<String>();
String[] arrStr = new String[list.size()];
list.toArray(arrStr);

转为数组

本回答被网友采纳
第2个回答  2016-05-11
hello java,have a good day 然后使用split(",")就可会以逗号为分隔符来获得一个字符串数组
相似回答