日期:2014-05-20  浏览次数:21487 次

如何读出字符串中的单个字符?
我现在要在一个.txt文件中读一些数据,原来的数据是一些字符串,比如:jajjALIjkkjjklizou。。。现在我要一个一个的读出,也就是说第一次读j,然后是a,一直这样下去,我写了个,可老是报错,麻烦大家给看下,谢谢。
import   java.io.*;
import   java.nio.ByteBuffer;
import   java.nio.channels.FileChannel;
import   java.util.*;

/**
  *   @author   huajun
  *  
  */
public   class   FileInput   {

private   ArrayList <Character>   collection   =   new   ArrayList <Character> ();

private   int   charlength;

private   Character[]   returns   =   null;

public   Character[]   Input()   {
File   file   =   new   File( "f:/test.txt ");

try   {
BufferedReader   in   =   new   BufferedReader(new   FileReader(file));
while   ((charlength   =   in.read())   !=   -1)   {
System.out.println((char)   charlength);
collection.add((char)   charlength);
}
in.close();
}   catch   (IOException   e)   {
//   TODO   自动生成   catch   块
e.printStackTrace();
}
System.out.println(collection);
charlength   =   collection.size();
System.out.println(charlength);
System.out.println( "before   returns! ");
for   (int   m   =   0;   m   <   charlength;   m++)   {
System.out.println(m);
System.out.println(collection.get(m));
returns[m]   =   collection.get(m);//就是这里出不来,字符都能被读到Arraylist里面,可转换的时候不行。
}

return   returns;
}

}
为什么?

------解决方案--------------------
帮顶啊 做个记号等高手来解答
------解决方案--------------------
ArrayList的get方法返回的是对象,你没有转型啊。。。
returns[m] = (Character)collection.get(m);
------解决方案--------------------
你的 returns 没有初始化过,也就是说要在 for (int m = 0; m < charlength; m++) 之前加上一行:returns = new Character[collection.size()]; 就可以了。

另:建议把以下三个成员变量去掉 private 放到方法体内。
private ArrayList <Character> collection = new ArrayList <Character> ();
private int charlength;
private Character[] returns = null;
------解决方案--------------------
你的private Character[] returns = null;没有初始化