Java的IO操作

作者: 程序o07 | 来源:发表于2018-07-03 14:14 被阅读0次

    Java的文件IO操作:

    有两种形式:字节流和字符流,字节流传输的是字节,返回的也是字节,而字符流传输的是字符,返回的也是字符。字节流可以处理任何数据,如音视频数据,而字符流仅能处理字符数据,如文本数据。

    字符流操作

    写字符到文件的例子:

    import java.io.File; 

    import java.io.FileWriter; 

    public class FileWriteDemo { 

    /**

         * 文件写操作

         */ 

    public static void main(String[] args) throws Exception { 

    // TODO Auto-generated method stub 

    //1.使用File对象指定一个文件 

    File f =new File("c:" + File.separator + "test.txt"); 

    //2.使用FileWriter对象实例化,并链接到指定文件 

    FileWriter fwr =new FileWriter(f, true); 

    //3.写入字符串数据 

    String str =" hello boy"; 

            fwr.write(str); 

    //4.清空缓存区 

            fwr.flush(); 

    //5.关闭输出流 

            fwr.close(); 

        } 

    读取字符类型的文件:

    import java.io.File; 

    import java.io.FileNotFoundException; 

    import java.io.FileReader; 

    import java.io.IOException; 

    public class FileDemo01 { 

    /**

         * 文件读操作

         */ 

    public static void main(String[] args) { 

    // TODO Auto-generated method stub 

    // 1.使用File对象指定从哪个文件读出数据 

    File f =new File("c:" + File.separator + "test.txt"); 

    // 2.定义输入流读入指定的文件 

    FileReader fr =null; 

    if (!f.exists()) { 

    System.out.print("Cannot find the file specified"); 

    System.exit(1); 

            } 

    try { 

    fr =new FileReader(f); 

    }catch (FileNotFoundException e) { 

                e.printStackTrace(); 

            } 

    // 3.开始读取数据到指定的缓冲区,读完后关闭输入流 

    char[] buf = new char[(int) f.length()]; 

    try { 

                fr.read(buf); 

                fr.close(); 

    }catch (IOException e) { 

                e.printStackTrace(); 

            } 

    // 4.打印读出的内容 

            System.out.print(buf); 

        } 

    字节流操作

    写字节到文件的例子:

    import java.io.File; 

    import java.io.FileNotFoundException; 

    import java.io.FileOutputStream; 

    import java.io.IOException; 

    public class FileDemo02 { 

    /**

         * @param args

         */ 

    public static void main(String[] args) { 

    // TODO Auto-generated method stub 

    // 定义写入的文件 

    File f =new File("c:" + File.separator + "test.txt"); 

    // 定义一个输出流对象 

    FileOutputStream fos =null; 

    try { 

    // 将输出流指定到文件本身 

    fos =new FileOutputStream(f, true); 

    }catch (FileNotFoundException e) { 

                e.printStackTrace(); 

            } 

    // 指定要写入的数据,将其转化为字节数组 

    String str ="hello world"; 

    byte[] b = str.getBytes(); 

    try { 

    // 写入字节数组到输出流中 

                fos.write(b); 

    // 关闭输出流 

                fos.close(); 

    }catch (IOException e) { 

                e.printStackTrace(); 

            } 

        } 

    读字节类型的文件的例子:

    import java.io.File; 

    import java.io.FileInputStream; 

    import java.io.FileNotFoundException; 

    import java.io.IOException; 

    public class FileDemo02 { 

    /**

         * @param args

         */ 

    public static void main(String[] args) { 

    // TODO Auto-generated method stub 

    // 定义要读出的文件 

    File f =new File("c:" + File.separator + "test.txt"); 

    // 定义一个输入流对象 

    FileInputStream fis =null; 

    // 判断文件是否存在 

    if (!f.exists()) { 

    System.out.print("the file is not exist"); 

    System.exit(1); 

            } 

    try { 

    // 将输入流指定到文件本身 

    fis =new FileInputStream(f); 

    }catch (FileNotFoundException e) { 

                e.printStackTrace(); 

            } 

    // 指定一个字节数组来存储读出的字节 

    byte[] b = new byte[(int) f.length()]; 

    try { 

    // 从字节输入流中读出字节到字节数组中 

                fis.read(b); 

    // 关闭输出流 

                fis.close(); 

    }catch (IOException e) { 

                e.printStackTrace(); 

            } 

    // 打印读出的字节并转换成字符显示 

    System.out.print(new String(b)); 

        } 

    附:通常在文件较大时,可以采用如下方式一个一个的读取,防止内存不够或读取缓慢:

    import java.io.File; 

    import java.io.FileInputStream; 

    import java.io.FileNotFoundException; 

    import java.io.IOException; 

    public class FileDemo02 { 

    /**

         * @param args

         */ 

    public static void main(String[] args) { 

    // TODO Auto-generated method stub 

    // 定义要读出的文件 

    File f =new File("c:" + File.separator + "test.txt"); 

    // 定义一个输入流对象 

    FileInputStream fis =null; 

    // 判断文件是否存在 

    if (!f.exists()) { 

    System.out.print("the file is not exist"); 

    System.exit(1); 

            } 

    try { 

    // 将输入流指定到文件本身 

    fis =new FileInputStream(f); 

    }catch (FileNotFoundException e) { 

                e.printStackTrace(); 

            } 

    // 指定一个字节数组来存储读出的字节 

    byte[] b = new byte[(int) f.length()]; 

    try { 

    // 一个一个字节的读取 

    // 定义返回的字节 

    int temp = 0; 

    // 定义一个字节数组的长度 

    int len = 0; 

    // 循环读取,直到read()返回-1,即指明文件已经到末尾,读完 

    while ((temp = fis.read()) != -1) { 

    // 将读取的字节存入到字节数组中 

    b[len] = (byte) temp; 

                    len++; 

                } 

    // 关闭输出流 

                fis.close(); 

    }catch (IOException e) { 

                e.printStackTrace(); 

            } 

    // 打印读出的字节并转换成字符显示 

    System.out.print(new String(b)); 

        } 

    字符流需要缓冲区的支持,而字节流不需要缓冲区的支持即可对文件本身进行读写。其实缓冲区就是一块 内存区域。如果想要强制性的清空缓冲区,可以使用FileWriter.flush()方法。一般情况下,文件多是 二进制形式,所以字节流用的较多。

    下面是一个文件复制的例子: 一次性读取然后一次性写入

    import java.io.File; 

    import java.io.FileInputStream; 

    import java.io.FileOutputStream; 

    import java.io.IOException; 

    public class FileCopy { 

    /**

         * @param args

         */ 

    public static void main(String[] args) { 

    // TODO Auto-generated method stub 

    // 判断命令是否正确 

    if (args.length != 2) { 

    System.out.println("wrong command"); 

    System.out.println("使用命令:FileCopy 源文件路径 目标文件路径"); 

    System.exit(1); 

            } 

    // 定义源文件和目标文件 

    File sf =new File(args[0]); 

    File df =new File(args[1]); 

    // 调用filecopy方法 

            fileCopy(sf, df); 

        } 

    public static void fileCopy(File sf, File df) { 

    // 定义输入流和输出流 

    FileInputStream fis =null; 

    FileOutputStream fos =null; 

    // 定义一个数据传输中间变量 

    byte[] buf = null; 

    // 判断源文件是否存在 

    if (!sf.exists()) { 

    System.out.println("The source file is not exist"); 

    System.exit(1); 

            } 

    // 读取指定源文件的内容并存到中间变量 

    try { 

    fis =new FileInputStream(sf); 

    byte[] b = new byte[(int) sf.length()]; 

                buf = b; 

    int len = 0, temp = 0; 

    while ((temp = fis.read()) != -1) { 

    b[len] = (byte) temp; 

                    len++; 

                } 

                fis.close(); 

    }catch (IOException e) { 

                e.printStackTrace(); 

            } 

    // 将中间变量中的内容写入到目标文件中 

    try { 

    fos =new FileOutputStream(df); 

                fos.write(buf); 

                fos.close(); 

    System.out.println("success"); 

    }catch (IOException e) { 

                e.printStackTrace(); 

            } 

        } 

    边读边写入

    import java.io.File; 

    import java.io.FileInputStream; 

    import java.io.FileOutputStream; 

    import java.io.IOException; 

    public class FileCopy { 

    /**

         * @param args

         */ 

    public static void main(String[] args) { 

    // TODO Auto-generated method stub 

    // 判断命令是否正确 

    if (args.length != 2) { 

    System.out.println("wrong command"); 

    System.out.println("使用命令:FileCopy 源文件路径 目标文件路径"); 

    System.exit(1); 

            } 

    // 定义源文件和目标文件 

    File sf =new File(args[0]); 

    File df =new File(args[1]); 

    // 调用filecopy方法 

            fileCopy(sf, df); 

        } 

    public static void fileCopy(File sf, File df) { 

    // 定义输入流和输出流 

    FileInputStream fis =null; 

    FileOutputStream fos =null; 

    // 判断源文件是否存在 

    if (!sf.exists()) { 

    System.out.println("The source file is not exist"); 

    System.exit(1); 

            } 

    // 指定源文件和目标文件并挂到输入流和输出流对象中 

    try { 

    fis =new FileInputStream(sf); 

    fos =new FileOutputStream(df); 

    // 边读边写入 

    int temp = 0; 

    while ((temp = fis.read()) != -1) { 

                    fos.write(temp); 

                } 

                fis.close(); 

                fos.close(); 

    System.out.println("copy success"); 

    }catch (IOException e) { 

                e.printStackTrace(); 

    System.out.println("copy fail"); 

            } 

        } 

    ❤提问/互动请留言,可直接在最底右下方"写留言即可

    ❤Java初高级一起学习分享,共同学习才是最明智的选择,喜欢的话可以我的学习群64弍46衣3凌9,或加资料群69似64陆0吧3(进群备注平台名)

    ❤如果觉得写得不错请点击“订阅”,每天更新全新的内容!

    ❤你们的喜欢和关注就是我最大的动力支撑!!!

    相关文章

      网友评论

        本文标题:Java的IO操作

        本文链接:https://www.haomeiwen.com/subject/hqnduftx.html