应用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给一个字符串 然后再来 处理?能否通过字符流类来处理写入文件?

解决方案 »

  1.   

    Scanner s=new Scanner(System.in);
    byte b[]=new byte[1024];
    int i=0;
    String t=s.nextLine();
    b=t.getBytes();
    改过的从屏幕读取 已经成功 只是在思考 有什么办法可以把System.in直接放进去比如FileInputStream f=new FileInputStream(System.in)  当然我知道这样不行 因为System.in是InputStream的对象 但是有什么办法可以转换为文件类么?
      

  2.   

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));