请高手指教!一个关于字符数组的问题!
我写了一个程序
目的是将文件text.txt的每行,根据方法readRecord( String type )中的type指定是否为string类型,组成字符串。每行返回的字符串组成字符数组。文件的行数就是字符数组的长度。
文件如下:
1,2,3
1,2,3
1,2,3
假设方法调用为:String type = new String(1,2);
a = readRecord( type );
要求返回的为:a[0]=‘1’,‘2’,3
a[1]=‘1’,‘2’,3
a[2]= ‘1’,‘2’,3
现在就是方法返回的数组里面取不到值,为null。不知道是不是这种返回数组的方法有问题。请高手指点!!
程序如下:
import java.io.*;
import java.util.*;
import java.util.StringTokenizer;
public class getSqlData
{
private String currentRecord = null;
private BufferedReader file;
private String path;
private StringTokenizer token;
static String nn = new String();
//创建文件对象
public getSqlData(String filePath) throws FileNotFoundException
{
path = filePath;
file = new BufferedReader(new FileReader(path));
}
//type是一个字符串,比如"1,2,3",就表示每行中的1,2,3个元素是string类型的,所以读出来的值要加"'"单引号
//返回的是一个字符数组,将每行组成的字符串都作为数组的每个元素
public String[] readRecord( String type )
{
int maxlength = 200;
String sep1 = ",";
String sep2 = "'";
String strings[] = new String[maxlength];
try
{
while ( (currentRecord = file.readLine()) != null )
{
int n = 0;
int i = 0;
String f = "";
StringTokenizer st = new StringTokenizer( currentRecord , ",");
while (st.hasMoreTokens())
{
n ++;
nn = Integer.toString(n);
if ( type.indexOf ( nn ) == -1 )
{
f += "," + st.nextToken();
}
else f += sep1 + sep2 + st.nextToken() + sep2;
}
strings[i] = f;
i ++;
}
return strings;
}
catch ( IOException d)
{
System.out.println("error!");
return strings;
}
}
public static void main(String args[])
{
String s = "d:/text.txt";
String v = "1,2";
try{
getSqlData test= new getSqlData(s);
System.out.println((test.readRecord(v))[1]);
}catch (FileNotFoundException e)
{
System.out.println("file not found!");
}
System.out.println("success");
}
}