Java IO 复习

Java IO 复习

Java IO 复习_第1张图片

示例:字符流-将用户在控制台中输入的内容保存到文件中

public static void main(String[] args) throws IOException {//psvm
    Scanner scanner = new Scanner(System.in);
    String data = scanner.next();
    FileWriter writer = new FileWriter("f.txt");//ctrl+alt+v
    writer.write(data);
    writer.flush();
    writer.close();
}

示例:将随机生成的字符串保存到文件中

public static void main(String[] args) throws IOException {//psvm
        File file = new File("F:\\f.txt");
        FileWriter writer = new FileWriter(file);//ctrl+alt+v
        BufferedWriter bw = new BufferedWriter(writer);
        for(int i =0;i<1000000000;i++) {
            String s = UUID.randomUUID().toString();
//            System.out.println(s);
            bw.write(s);
        }
        bw.flush();
        bw.close();
    }

示例:读取文件

  • 实现一
public static void main(String[] args) throws IOException {//psvm
    File file = new File("F:\\安装GCC.txt");
    FileReader reader = new FileReader(file);
  
    int read = reader.read();   //read() 一次读取一个字符
    System.out.print((char)read);

    while(read != -1){
      read = reader.read();
        System.out.print((char)read);
    }
    reader.close();
}
  • 实现二
public static void main(String[] args) throws IOException {//psvm
   File file = new File("F:\\安装GCC.txt");
   FileReader reader = new FileReader(file);

   char[] buf = new char[64];
   int len = reader.read(buf); //将数据读取到buf中,返回读取到的字符的个数
   while(len != -1){
       System.out.println(new String(buf,0,len));
       len = reader.read(buf);//
   }
   reader.close();
}
  • 实现三(重点掌握)
public static void main(String[] args) throws IOException {//psvm
    File file = new File("F:\\安装GCC.txt");
    FileReader reader = new FileReader(file);
    char[] buf = new char[64];
    int len = -1;
    while((len = reader.read(buf)) != -1){
        System.out.println(new String(buf,0,len));
    }
    reader.close();
}

示例:字符流-txt文件拷贝

public static void main(String[] args) throws IOException {//psvm
    File file1 = new File("F:\\sources.txt");
    File file2 = new File("F:\\aim.txt");

    FileReader reader = new FileReader(file1);
    FileWriter writer = new FileWriter(file2);

    int len =-1;
    char[] buf = new char[128];

    while ((len = reader.read(buf)) != -1){
        writer.write(new String(buf,0,len));
    }

    writer.flush();
    writer.close();
    reader.close();
}

示例:复制音频文件

public static void main(String[] args) throws IOException {//psvm
    File sources = new File("F:\\微购 实体类 数据库工具类 编写.wmv");
    File aim = new File("F:\\微购 实体类 数据库工具类 编写2.wmv");

    FileInputStream fis = new FileInputStream(sources);
    FileOutputStream fos = new FileOutputStream(aim);
    byte[] buf = new byte[256];
    int len =-1;
    while ((len = fis.read(buf)) != -1){
        fos.write(buf,0,len);
    }
    fos.flush();
    fos.close();
    fis.close();
}

你可能感兴趣的:(Java,IO,IO,Java,文件流,Java)