zoukankan      html  css  js  c++  java
  • Java File文件的读写

    今天的内容:

    FileInputStream:

    该流可以从文件中读取数据,它的对象可以用new创建。

    使用字符串类型的文件名创建一个输入流对象读取文件:

    InputStream f = new FileInputStream("c:/java/hello");

    也可以使用一个文件对象来创建一个输入流对象读取文件,首先要用File()方法来创建一个文件对象:

    File f = new File("c:/java/hello");
    InputStream out = new File InputStream(f);

    FileOutputStream的创建方法类似.(如果文件不存在则会创建该文件)

    两个类的综合实例:

    package some;
    import java.io.*;
    
    public class some{
        public static void main(String[] args) {
            try {
                byte bWrtie[] = {11,21,3,40,5};
                OutputStream os = new FileOutputStream("test.txt");
                for (int x = 0; x < bWrtie.length; x++) {
                    os.write(bWrtie[x]);
                }
                os.close();
                
                InputStream is = new FileInputStream("test.txt");
                int size = is.available();
                for (int i = 0; i < size; i++) {
                    System.out.print((char)is.read()+"  ");
                }
                is.close();
            } catch (IOException e) {
                // TODO: handle exception
                System.out.println("Exception");
            }
        }
    }

    由于文件写入的时候使用的是二进制格式所以输出会有乱码,解决方案:

    package some;
    import java.io.*;
    
    public class some{
        public static void main(String[] args) throws IOException {
            File f = new File("a.txt");
            FileOutputStream fop = new FileOutputStream(f);
            OutputStreamWriter writer = new OutputStreamWriter(fop,"gbk");
            writer.append("中文输入");
            writer.append("
    ");// /r/n是常用的换行转义字符,有的编译器不认识/n
            writer.append("English");
            writer.close();//关闭写入流,同时把缓冲区的内容写到文件里
            fop.close();//关闭输出流
            FileInputStream fip =new FileInputStream(f);
            InputStreamReader reader = new InputStreamReader(fip,"gbk");
            StringBuffer s = new StringBuffer();
            while (reader.ready()) {
                s.append((char) reader.read());
            }
            System.out.println(s.toString());
            reader.close();
            fip.close();
        }
    }

    ByteArrayInputStream类:

    创建方式:

    //用接受字节数组作为参数
    ByteArrayInputStream bArray = new ByteArrayInputStream(byte[] a);
    /*用一个接受字节数字和两个整形变量off、len。前者表示第一个读取的字节,len表示读取字节的长度*/
    ByteArrayInputStream bArray = new ByteArrayInputStream(byte[] a, int off, int len);

    ByteArrayOutputStream类的创建类似
    明天的打算:继续学习

    问题:无

  • 相关阅读:
    【Linux_Unix系统编程】Chapter4 文件IO
    【Unix网络编程】chapter6 IO复用:select和poll函数
    【Unix网络编程】 chapter5 TCP客户,服务器程序实例
    【Unix网络编程】chapter3 套接字编程简介
    VS自动编译脚本
    【Python编程:从入门到实践】chapter4 操作列表
    【Python编程:从入门到实践】chapter3 列表简介
    【Python编程:从入门到实践】chapter2 变量和简单数据类型
    【Unix网络编程】chapter2传输层:TCP,UDP和SCTP
    vim配置编辑php
  • 原文地址:https://www.cnblogs.com/MXming/p/13399674.html
Copyright © 2011-2022 走看看