当前位置: 代码迷 >> Java相关 >> 求教! 如何逐个读取文件中的字符串??
  详细解决方案

求教! 如何逐个读取文件中的字符串??

热度:109   发布时间:2007-03-29 23:34:07.0
求教! 如何逐个读取文件中的字符串??
比如我有个text.txt的文件,其中只有一行字符,为"first second three",不包括双引号,请问要如何把每个字符串分别读出来?比如第一次读出first,第二次读出second
搜索更多相关的解决方案: 字符  文件  

----------------解决方案--------------------------------------------------------
可以考虑用StringTokenizer
----------------解决方案--------------------------------------------------------

先用流把文件读出形成String,然后用split


----------------解决方案--------------------------------------------------------
可以考虑用正则表达式或者用StreamTokenizer
----------------解决方案--------------------------------------------------------

谢谢各位了,不过具体的实现过程可否看下,thank you


----------------解决方案--------------------------------------------------------
用Scanner.
程序代码:

import java.util.Scanner;
import java.io.*;
public class ReadWords{
public static void main(String[] args)throws Exception{
Scanner scan =new Scanner(new File(\"test.txt\"));
while(scan.hasNext()) System.out.println(scan.next());
scan.close();
}
}

随手写的,没测试过,楼主试试.
----------------解决方案--------------------------------------------------------

import java.io.*;
import java.util.Scanner;
class readString
{

public void getString()//从文件中读取数据
{
try
{
BufferedInputStream bin=new BufferedInputStream(new FileInputStream("mytext.txt"));
int len=bin.available();
byte [] str=new byte[len];
bin.read(str);
String s=new String(str,0,str.length); //将字节数组转为字符串
String[] newStr=s.split("\\s");

System.out.println("the data is:");
for(int j=0;j<newStr.length;j++)
{
System.out.println(newStr[j]);
}
bin.close();
}
catch(IOException e)
{System.out.print(e.toString());}
}


public void setString()//向文件中写入数据
{
try
{
BufferedOutputStream bout=new BufferedOutputStream(
new FileOutputStream("mytext.txt",true));//可追加
Scanner in=new Scanner(System.in);
System.out.print("would you like append the data?(Y/N) ");
String result="";
String isAppend=in.next();
if(isAppend.equalsIgnoreCase("Y"))
{
System.out.print("append data:");
result=result+in.next()+in.nextLine();//“in.next()”的作用屏蔽回车键,然后键入新的数据

byte[] str=result.getBytes();
bout.write(str,0,str.length);
bout.flush();
bout.close();
}

}
catch(IOException e)
{
System.out.print(e.toString());
}
}

}
class IOText
{
public static void main(String [] agrs)
{
readString rs=new readString();
rs.setString();
rs.getString();

}
}

写得很乱
不过可以测试了


----------------解决方案--------------------------------------------------------
哇,楼上写小说啊,吃饱了撑着。。。
----------------解决方案--------------------------------------------------------

还是Scanner强呀
谢谢各位了


----------------解决方案--------------------------------------------------------
  相关解决方案