JAVA之IO字节流的基础应用

import java.io.*;
public class IO_字节流 {
    public static void main(String[] args) {
        //使用OutputStream创建一个文本文档,并存入文字
//        try{
//           // OutputStream os=new FileOutputStream("text.txt");//会自动创建一个文件 text(文件名自取)
//            OutputStream os=new FileOutputStream("text.txt",true);//加上true后,添加文字将不会把原有的文字覆盖,而是加入到原有文字的后面
//           // String str="你好啊!";
//            String str="你好";
//            byte[] b=str.getBytes();
//            os.write(b);//写入
//            os.close();
//        }catch (Exception e){
//            e.printStackTrace();
//        }
        //使用InputStream读取text文本文档
        try {//相对路径
            InputStream in = new FileInputStream("文件路径");
            InputStreamReader in2=new InputStreamReader(in,"UTF-8");//如果有中文,则使用UTF-8,不然输出为乱码
            char[]a=new char[100];
            in2.read(a);//读取
            in2.close();
            for(char b:a){
                if(b=='\0'){//遇到空格则停止
                    break;
                }else{
                    System.out.print(b);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_62731133/article/details/124179731