当前位置: 代码迷 >> J2SE >> 关于OutputStream类型的write方法,该如何解决
  详细解决方案

关于OutputStream类型的write方法,该如何解决

热度:69   发布时间:2016-04-24 12:18:56.0
关于OutputStream类型的write方法
Java code
功能描述:从键盘输入一串字符,直到输入回车符结束,然后从屏幕输出并将其存入a.txt文件中。输入使用System.in.read();输出使用System.out.write();    public static void main(String[] args){        int ch;        try {            FileOutputStream fos = new FileOutputStream("a.txt");            System.out.print("请输入(回车符结束):");            while((ch=System.in.read())!='\n'){//下面这两行为什么ch明明是int类型的数据,控制台和a.txt中可以显示输入的字符和汉字?                System.out.write(ch);                fos.write(ch);            }//还有下面这行代码中write的参数不应该是int类型的吗,怎么可以写回车?            System.out.write('\n');            System.out.println("输出到文件完毕,请查收!");        }catch (IOException e) {            System.out.println(e.toString());        }        }


------解决方案--------------------
Java code
import java.io.*;public class Demo1 {    public static void main(String[] args){        int ch;        try {            FileOutputStream fos = new FileOutputStream("a.txt");            System.out.print("请输入(回车符结束):");            while((ch=System.in.read())!='\n'){//下面这两行为什么ch明明是int类型的数据,控制台和a.txt中可以显示输入的字符和汉字?//控制台和文本文件会自动将数值安装编码表如(UTF8编码)转换为字符显示//文本文件默认就是这样转换为字符显示,也可以用16进制查看,其存储的值一样                System.out.write(ch);                fos.write(ch);            }//还有下面这行代码中write的参数不应该是int类型的吗,怎么可以写回车?//编译器将System.out.write('\n')自动转换为字符char='\n'的int值处理            System.out.write('\n');            System.out.println("输出到文件完毕,请查收!");        }catch (IOException e) {            System.out.println(e.toString());        }    }}
  相关解决方案