日期:2014-05-20  浏览次数:20692 次

用FileInputStream写入文件的问题
应用FileInputStream和FileOutputStream设计程序,接收终端窗口的用户输入,并将用户输入的内容写入一个名为“data1.txt”的文件中,从文件中读取字节,并显示到终端窗口。

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;


public class FileTest1 {

/**
* @param args
*/
public static void main(String[] args) {
//------创建文件
File f=new File("data1.txt");
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


//--------屏幕读取
Scanner s=new Scanner(System.in);
byte b[]=new byte[1024];
int i=0;
while(s.hasNextByte()){
b[i]=s.nextByte();
i++;
}


//---输入到文件
String content;
try {
FileOutputStream out=new FileOutputStream(f);
out.write(b);
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

//---文件读取输出到屏幕
try {
FileInputStream fin=new FileInputStream(f);
int temp=fin.read();
while(temp!=-1){
System.out.println( (char)temp );
temp=fin.read();
}


fin.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}

}


我的代码如下 有错误 没抛出异常 System.in是否一定只能通过Scanner给一个字符串 然后再来 处理?能否通过字符流类来处理写入文件?

------解决方案--------------------
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));