import java.util.*;import java.io.*;public class File { static String tt[] = new String[5];  //   为什么一定要过定长度   没有别的办法了吗? public static void main(String[] args) {
try {
String file = "C:\\text.txt";
String str = new String(); FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr); while ((str = br.readLine()) != null) { str = str.trim();
int i = 0;
StringTokenizer fenxi = new StringTokenizer(str, ",");
int number = fenxi.countTokens(); while (fenxi.hasMoreTokens()) {
tt[i] = fenxi.nextToken();
System.out.println(tt[i]);
i++;
} } br.close();
fr.close(); } catch (IOException e) {
System.out.println(e);
} }
}
读这个文件并不能去除 空格, 当读到空格时会抛异常
如何改进!请问读文件数据,放入到数组中
还有什么方法
帮忙写一下!

解决方案 »

  1.   

    你可以将增加空格(' ')标记器中的分隔符,即将StringTokenizer(str, ",")改为StringTokenizer(str, " ,")
      

  2.   

    楼主抛异常应该不是空格的问题而是数组越界问题吧,你程序的number根本没用import java.util.*;import java.io.*;public class FileDemo { static String tt[];// = new String[5];  //   为什么一定要过定长度   没有别的办法了吗? public static void main(String[] args) {
    try {
    String file = "text.txt";
    String str = new String(); FileReader fr = new FileReader(file);
    BufferedReader br = new BufferedReader(fr); while ((str = br.readLine()) != null) { str = str.trim();
    int i = 0;
    StringTokenizer fenxi = new StringTokenizer(str, ",");
    int number = fenxi.countTokens();
    tt = new String[number]; while (fenxi.hasMoreTokens()) {
    tt[i] = fenxi.nextToken();
    System.out.println(tt[i]);
    i++;
    } } br.close();
    fr.close(); } catch (IOException e) {
    System.out.println(e);
    } }
    }
      

  3.   

    是数组越界问题
     对number根本没用
    关键是怎么改啊!
      

  4.   

    “是数组越界问题
     对number根本没用
    关键是怎么改啊!”
     sorry 没看仔细,以为你没该
    搞定了Thank You !    believefym(feng)
      

  5.   

    不是已经放到数组里面了吗,或者不要用数组了,用Collection更简单import java.util.*;import java.io.*;public class FileDemo { //static String tt[];// = new String[5]; // 为什么一定要过定长度 没有别的办法了吗?
    static List<String> list = new ArrayList<String>(); public static void main(String[] args) {
    try {
    String file = "text.txt";
    String str = new String(); FileReader fr = new FileReader(file);
    BufferedReader br = new BufferedReader(fr); while ((str = br.readLine()) != null) { str = str.trim();
    //int i = 0;
    StringTokenizer fenxi = new StringTokenizer(str, ",");
    int number = fenxi.countTokens();
    //tt = new String[number]; while (fenxi.hasMoreTokens()) {
    //tt[i] = fenxi.nextToken();
    //System.out.println(tt[i]);
    //i++;
    list.add(fenxi.nextToken());
    } } br.close();
    fr.close(); } catch (IOException e) {
    System.out.println(e);
    }

    System.out.println(list); }
    }