当前页面: 开发资料首页 → J2SE 专题 → 请教关于文件读取的问题
请教关于文件读取的问题
摘要: 请教关于文件读取的问题
我有一个.txt文件,里面存有几百个1到100的数字(不知道具体多少个),中间都是用空格隔开的.我现在想把这些数字读出来存到一个数组或向量里,请问应该怎么做?我IO这部分学的不好,请多指教.谢谢.
mark学习UP
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class FileToArray {
public static void main(String[] args) {
// TODO Auto-generated method stub
int Temp;
String str="";
String mm[] = null;
try{
FileInputStream fis = new FileInputStream("G://workspace//test//filetoarray//a.txt");
while((Temp = fis.read())!=-1){
str += (char)Temp;
}
mm = str.split(" ");
}
catch(FileNotFoundException e)
{
System.out.println(e);
}
catch(IOException e){
System.out.println(e);
}
finally{
for(int i = 0; i< mm.length; i++)
{
System.out.println(mm[i]);
}
}
}
}
中间只有空格么?不考虑有换行的话可以这么写:
File f = new File("test.txt") ;
BufferedReader in = new BufferedReader( new FileReader(f) ) ;
String s = in.readLine() ;
String[] ss = s.split(" ") ;
int[] count = new int[ss.length] ;
for (int i = 0; i
{
count[i] = new Integer(ss[i]) ;
}
最后的count[]就是得到的数组
3楼顶
考虑分行情况,以下程序经测试是正确的
/**文件路径
* @param path
* @return
* @throws IOException
*/
public int[] readnumber(String path) throws IOException{
File file=new File(path);
if(!file.exists()||file.isDirectory())
throw new FileNotFoundException();
BufferedReader br=new BufferedReader(new FileReader(file));
String temp=null;
StringBuffer sb=new StringBuffer();
temp=br.readLine();
while(temp!=null){
sb.append(temp+" ");
temp=br.readLine();
}
String[] array_str=sb.toString().split(" ");
int[] array_int=new int[array_str.length];
for(int i=0;i
array_int[i]=Integer.parseInt(array_str[i]);
return array_int;
}
谢谢大家!