A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

①读取文档的内容:

public class ReadFile {
    public static void main(String[] args){
        readFile("C:\\Users\\Administrator\\Desktop\\构造方法.txt");
    }
    public static void readFile(String fielname){
        //创建流
        try {
            InputStream is = new FileInputStream(fielname);
            //创建缓存区域
            byte buffer[] = new byte[is.available()];
            //读取文件字节
            is.read(buffer);
            //对字节处理
            String str = new String(buffer);
            System.out.println(str);
            //关闭流
            is.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
②对文档的输入:这里对输入的内容有点不一样(注意汉字的写入方式)

public class WriteFile {
    public static void main(String[] args) throws IOException{
        WriteFile wf = new WriteFile();
        wf.writefile("256", "D:\\text.txt");
    }
    public void writefile(String content,String fileName) throws IOException{
        //创建流
        OutputStream os = new FileOutputStream(fileName);

        //获取所需要获得的内容
        byte[] bytes = content.getBytes();

        //写出内容
        os.write(bytes);

        os.write(123);//写的是123对应的ASCII码,在txt文档中显示的是{
        os.write(123456);//其实写的是低八位(一个字节)的数据,>255的数写进去的仅仅是它对应的二进制的低八位

        //如果需要实现将一个int类型的数据写进去的话,首先需要做一个封装
        DataOutput dinput = new DataOutputStream(os);
        int x=123456;
        dinput.writeInt(x);



        String str1 ="你好";
        os.write(str1.getBytes("gbk"));   // 写汉字进去,gbk必须加双引号

        //刷新
        os.flush();
        //停止流
        os.close();


        InputStream is = new FileInputStream(fileName);
        is.read(bytes);
        is.close();
    }      

}
---------------------
【转载,仅作分享,侵删】
作者:lzq1326253299
原文:https://blog.csdn.net/lzq1326253299/article/details/81947645
版权声明:本文为博主原创文章,转载请附上博文链接!

1 个回复

倒序浏览
奈斯,感谢分享
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马