文件和流

IO作用:解决设备和设备之间数据传输问题,内存->硬盘,硬盘->内存,键盘数据->内存数据存到硬盘上,就做到了永久保存,数据一般是以文件形式保存到硬盘上,sun用File描述文件文件夹

File构造方法

File file = new File(String pathname);

public class Test {
    public static void main(String[] args) {
        File file = new File("E:\\test.txt");
        try {
            file.createNewFile();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

在文件夹里创建文件
File file = new File (String 文件夹, String 文件名);

public class Test {
    public static void main(String[] args) {
        File file = new File("E:\\k","test.txt");
        try {
            file.createNewFile();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

在文件夹中的文件夹里创建文件

public class Test {
    public static void main(String[] args) {
        File file1 = new File("E:\\k\\k")
        File file = new File(file1,"test.txt");
        try {
            file.createNewFile();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

绝对路径 & 相对路径

相对路径不能跨盘
相对路径:../../Test1.txt, ./Test1.txt = Test1.txt

创建

创建文件:
createNewFile();
创建单层文件夹:
mkdir();

//在E盘里创建一个叫k的文件夹
File file = new File("E:/k");
try{
  file.mkdir();
}catch(Exception e){
  e.printStackTrace();
}

mkdir
public boolean mkdir()
创建此抽象路径名指定的目录。
返回:
当且仅当已创建目录时,返回 true;否则返回 false

File file = new File("E:.k.txt");
boolean b = file.mkdir();
System.out.println(b);

创建多层文件夹:
mkdirs();

File file = new File("E:/a/b/c/d");
file.mkdirs();

文件重命名:

File srcFile = new File("E:/test.txt");
File destFile = new File("E:/k.txt");
srcFile.renameTo(destFile);

删除文件(夹):

File srcFile = new File("E:/test.txt");
File destFile = new File("E:/k.txt");
srcFile.delete();

删除成功返回true,否则返回false

存在:
exists();
System.out.println(srcFile.exists());
boolean型, 存在返回true,否则返回false

是不是文件: src.isFile(); boolean型

是不是目录:isDirectory(); boolean

是不是一个目录: isDirectory(); boolean

是否被隐藏: isHidden(); boolean

是否是绝对路径: isAbsolute(); boolean

获取文件名: getName(); String

获取(假)绝对路径: getPath(); String

获取绝对路径: getAbsolutePath(); String

获取文件内容字节个数: long length();

获取最后一次修改时间: lastModified();

获取次抽象路径名表示的目录中的所有子文件(夹):
File[] listFiles(); 数组

File file = new File("E:/k");
File[] list = file.listFiles();
for(File file1 : list){
  System.out.println(file1.getName());
}
//或取E盘k文件夹下的文件(夹)名
public class Test {
    public static void main(String[] args) {
        File file = new File("E:/k");
        test(file);
    }
    public static void test(File file){
        File[] files = file.listFiles();
        for (int i = 0; i < files.length; i++){
            if (files[i].isFile()){
                System.out.println(files[i].getName());
            }else {
                test(files[i]);
            }
        }
    }
}
//获取E盘k文件夹里所有文件名

获取文件夹里的所有文件:
递归思想

public class Practice {
    public static void main(String[] args) {
       PrintFiles("e/neusoft");
    }
    public static void PrintFiles(String path){
        File file1 = new File(path);
        File[] files = file1.listFiles();
        for (File file : files){
            if (file.isFile()) {
                System.out.println(file.getName());
            }
            else if (file.isDirectory()){
                System.out.println(file.getAbsolutePath());
                PrintFiles(file.getAbsolutePath());
            }
        }
    }
}

流是指一连串流动的字符,是以先进先出方式发送信息的通道。
通过流来读写文件。
字符,字节流:

  • 往文本文档里写东西是字符流,字符输入流Reader,字符输出流Writer
  • 往word里写东西是字节流,字节输入流InputStream,字符输出流OutputStream
    输入,输出流:
  • 往内存里读叫输入流,InputStream 和Reader作为基类
  • 从内存出叫输出流,OutputStream和Writer作为基类

文本文件的读写:

  • 用FileInputStream和FileOutputStream读写
  • 用BufferedReader和BufferedWriter读写

二进制文件读写:

  • 使用DataInputStream和DataOutputStream读写

使用FileInputStream读写:


image.png

InputStream类常用方法:
int read( ) 读取一个字节
int read(byte[] b) 读取一批字节
int read(byte[] b,int off,int len)
void close( )
子类FileInputStream常用的构造方法
FileInputStream(File file)
FileInputStream(String name)

byte[] buffer = new byte[10];
buffer[0] = 97;
buffer[1]=98;//b
String string = new String(buffer,0//offset,2//length);
System.out.println(string);

read()

File file = new File("e:/test.txt");
System.out.println(file.length());
byte[] buffer = new byte[(int)file.length()];
FileInputStream fileInputStream = new FileInputStream(file);
int index = 0;
byte content = (byte)fileInputStream.read();//读取文件的一个字节
while (content != -1){
  buffer[index] = content;
  index++;
  content = (byte)fileInputStream.read();
}
System.out.println(Arrays.toString(buffer));
String string = new String(buffer,0,index);
System.out.println(string);

read(byte[] b)

public static void main(String[] args) throws IOException {
        // write your code here

        File file = new File("d:/我的青春谁做主.txt");
        FileInputStream fileInputStream = new FileInputStream(file);

        byte[] buffer = new byte[SIZE];//保存从磁盘读到的字节


        int len = fileInputStream.read(buffer);//第一次读文件中的100个字节
        while (len != -1)
        {
            String string = new String(buffer,0, len);
            System.out.println(string);
            //读下一批字节
            len = fileInputStream.read(buffer);
        }
    }

写文件:

FileOutputStream fileOutputStream = new FileOutputStream("e:/test.txt");
        String string = "good job";
        byte[] words = string.getBytes();
        fileOutputStream.write(words,0,words.length);

OutputStream类常用方法
void write(int c)
void write(byte[] buf)
void write(byte[] b,int off,int len)
void close( )
子类FileOutputStream常用的构造方法
FileOutputStream (File file)
FileOutputStream(String name)
FileOutputStream(String name,boolean append)
1、前两种构造方法在向文件写数据时将覆盖文件中原有的内容
2、创建FileOutputStream实例时,如果相应的文件并不存在,则会自动创建一个空的文件

复制文件内容
文件“我的青春谁做主.txt”位于D盘根目录下,要求将此文件的内容复制到
C:\myFile\my Prime.txt中
实现思路:
创建文件“D:\我的青春谁做主.txt”并自行输入内容
创建C:\myFile的目录。
创建输入流FileInputStream对象,负责对D:\我的青春谁做主.txt文件的读取。
创建输出流FileOutputStream对象,负责将文件内容写入到C:\myFile\my Prime.txt中。
创建中转站数组words,存放每次读取的内容。
通过循环实现文件读写。
关闭输入流、输出流

 File file = new File("e:/Test.txt");
        File file1 = new File("d:/myFile");
        try{
            file1.mkdir();
        }catch (Exception e){
            e.printStackTrace();
        }
        File file2 = new File("d:/myFile/my Prime.txt");
        FileInputStream fileInputStream = new FileInputStream(file);
        FileOutputStream fileOutputStream = new FileOutputStream(file2);
        byte[] buffer = new byte[5];
        int read_len = fileInputStream.read(buffer);
        while (read_len != -1){
            String string = new String(buffer,0,read_len);
            System.out.println(string);
            byte[] words = string.getBytes();
            fileOutputStream.write(words,0,words.length);
            read_len = fileInputStream.read(buffer);
        }
File file = new File("e:/c2fdfc039245d688c56332adacc27d1ed21b2451.jpg");
        File file1 = new File("d:/myFile");
        if (!file1.exists()){
            file1.mkdir();
        }
        File file2 = new File("d:/myFile/my Prime.jpg");
        FileInputStream fileInputStream = new FileInputStream(file);
        FileOutputStream fileOutputStream = new FileOutputStream(file2);
        byte[] buffer = new byte[10];
        int read_len = fileInputStream.read(buffer);
        while (read_len != -1){
            fileOutputStream.write(buffer,0,buffer.length);
            read_len = fileInputStream.read(buffer);
        }
        fileInputStream.close();
        fileOutputStream.close();

使用字符流读写文件

使用FileReader读取文件

public static void main(String[] args) throws IOException {
        //
        FileReader fileReader = new FileReader("D:/我的青春谁做主.txt");

        char[] array = new char[100];
        int length = fileReader.read(array);
        StringBuilder sb = new StringBuilder();//拼接字符串
        while (length != -1)
        {
            sb.append(array);//追加字符串
            length = fileReader.read(array);
        }

        System.out.println(sb.toString());
        fileReader.close();

    }
FileReader fileReader = new FileReader("e:/test.txt");
        char[] chars = new char[5];
        int length = fileReader.read(chars);
        StringBuilder stringBuilder = new StringBuilder();
        int count = 0;
        while (length != -1){
            count++;
            System.out.println(count);
            stringBuilder.append(chars);
            Arrays.fill(chars,'\u0000');
            length = fileReader.read(chars);
            
        }
        System.out.println(stringBuilder.toString());
        fileReader.close();

BufferedReader类

使用FileReader类与BufferedReader类
BufferedReader类是Reader类的子类
BufferedReader类带有缓冲区
按行读取内容的readLine()方法


image.png
public static void main(String[] args) throws IOException {
        FileReader fileReader = new FileReader("D:/我的青春谁做主.txt");

        BufferedReader bufferedReader = new BufferedReader(fileReader);

        String strContent = bufferedReader.readLine();
        StringBuilder sb = new StringBuilder();
        while (strContent != null)
        {
            sb.append(strContent);
            sb.append("\n");
            sb.append("\r");
            strContent = bufferedReader.readLine();
        }

        System.out.println(sb.toString());
        fileReader.close();
        bufferedReader.close();
    }

使用FileWriter写文件

FileWriter fileWriter = new FileWriter("e:/test.txt");
fileWriter.append("hello world");
fileWriter.flush();
fileWriter.close();

如何提高字符流写文本文件的效率?
使用FileWriter类与BufferedWriter类
BufferedWriter类是Writer类的子类
BufferedWriter类带有缓冲区


image.png
public class BufferedWriterTest {
    public static void main(String[] args) {
        FileWriter fw=null;
        BufferedWriter bw=null;
        FileReader fr=null;
        BufferedReader br=null;
        try {
           //创建一个FileWriter 对象
           fw=new FileWriter("D:\\myDoc\\hello.txt"); 
           //创建一个BufferedWriter 对象
           bw=new BufferedWriter(fw); 
           bw.write("大家好!"); 
           bw.write("我正在学习BufferedWriter。"); 
           bw.newLine(); 
           bw.write("请多多指教!"); 
           bw.newLine();               
           bw.flush();
                       
           //读取文件内容
            fr=new FileReader("D:\\myDoc\\hello.txt"); 
            br=new BufferedReader(fr); 
            String line=br.readLine();
            while(line!=null){ 
                System.out.println(line);
                line=br.readLine(); 
            }
          
            fr.close(); 
           }catch(IOException e){
                System.out.println("文件不存在!");
           }finally{
               try{
                   if(fw!=null)
                       fw.close();
                   if(br!=null)
                       br.close();
                   if(fr!=null)
                       fr.close();  
               }catch(IOException ex){
                    ex.printStackTrace();
               }
           }
    }
}

文本拷贝

FileReader fr = new FileReader("e:/test.txt");
        FileWriter wr = new FileWriter("d:/myFile/my Prime.txt");
        BufferedReader reader = new BufferedReader(fr);
        BufferedWriter writer = new BufferedWriter(wr);
        StringBuffer str = new StringBuffer();
        String line = reader.readLine();
        while (line != null){
            str.append(line);
            str.append("\n");
            str.append("\t");
            wr.flush();
            line = reader.readLine();
        }
        System.out.println(str.toString());
        String string = str.toString().replace("{name}","golden");
        string = string.toString().replace("{type}","dog");
        string = string.toString().replace("{master}","zabrath");
        System.out.println(string);
        writer.write(string);
        writer.flush();

练习 统计某个文件夹下所有java文件代码行数之和:

File file = new File("C:\\Users\\Administrator\\IdeaProjects\\jemalsjava\\src\\com\\company\\");
        File[] arr = file.listFiles();
        int totalCount = 0;
        for (File file1 : arr){
            FileReader fileReader = new FileReader(file1);
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            int countLine = 0;
            String strLine = bufferedReader.readLine();
            while (strLine != null){
                countLine++;
                strLine = bufferedReader.readLine();
            }
            totalCount += countLine;
        }
        System.out.println(totalCount);
package com.company;

import java.io.*;

/**
 * Created by ttc on 2018/6/5.
 */
public class CodeLinesCount {
    public static int CountLines(String filename) throws IOException {
        FileReader fileReader = new FileReader(filename);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        int count = 0;
        String strLine = bufferedReader.readLine();
        while(strLine != null)
        {
            count++;
            strLine = bufferedReader.readLine();
        }
        System.out.println(count);
        return count;
    }
    public static void main(String[] args) throws IOException {
//        CountLines("d:/Main.java");
        File file = new File("D:\\javacode");
        File[] files = file.listFiles();
        int sum = 0;
        for(File file1 : files)
        {
            System.out.println(file1.getPath());
            int count = CountLines(file1.getPath());
            sum += count;
        }
        System.out.println(sum);
    }
}

DataOutputStream和DataInputStream

DataOutputStream数据输出流: 将java基本数据类型写入数据输出流中。
DataInputStream数据输入流:将DataOutputStream写入流中的数据读入。

DataOutputStream中write的方法重载:

继承了字节流父类的两个方法:
(1)void write(byte[] b,int off,int len);
(2)void write(int b);//写入UTF数值,代表字符
注意字节流基类不能直接写入string 需要先将String转化为getByte()转化为byte数组写入
特有的指定基本数据类型写入:
(1)void writeBoolean(boolean b);//将一个boolean值以1byte形式写入基本输出流。
(2)void writeByte(int v);//将一个byte值以1byte值形式写入到基本输出流中。
(3)void writeBytes(String s);//将字符串按字节顺序写入到基本输出流中。
(4)void writeChar(int v);//将一个char值以2byte形式写入到基本输出流中。先写入高字节。写入的也是编码值;
(5)void writeInt(int v);//将一个int值以4byte值形式写入到输出流中先写高字节。
(6)void writeUTF(String str);//以机器无关的的方式用UTF-8修改版将一个字符串写到基本输出流。该方法先用writeShort写入两个字节表示后面的字节数。

DataInputStream中read方法重载:

继承了字节流父类的方法:
int read();
int read(byte[] b);
int read(byte[] buf,int off,int len);
对应write方法的基本数据类型的读出:
String readUTF();//读入一个已使用UTF-8修改版格式编码的字符串
boolean readBoolean;
int readInt();
byte readByte();
char readChar();
注意:
基本数据类型的写入流和输出流,必须保证以什么顺序按什么方式写入数据,就要按什么顺序什么方法读出数据,否则会导致乱码,或者异常产生。

public class DataStream {
    public static void main(String[] args) throws IOException {
        String[] strings = {"main","flush","String","FileOutputStream","java.io.*"};
        FileOutputStream fileOutputStream = new FileOutputStream("e:/output.txt");
        DataOutputStream dataOutputStream = new DataOutputStream(fileOutputStream);

        for(String string : strings)
        {
            int strlen = string.length();
            dataOutputStream.writeShort(strlen);
            dataOutputStream.writeBytes(string);
        }


        dataOutputStream.flush();
        dataOutputStream.close();

        FileInputStream fileInputStream = new FileInputStream("e:/output.txt");
        DataInputStream dataInputStream = new DataInputStream(fileInputStream);

        while(true)
        {
            try {
                short len = dataInputStream.readShort();
                byte[] bytes = new byte[len];
                dataInputStream.read(bytes);
                String string = new String(bytes,0,bytes.length);
                System.out.println(string);
            }
            catch (EOFException ex)
            {
                break;
            }

        }

    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容