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();
}
}
写得很乱
不过可以测试了