java day 17

I/O

  • java I/O读写基本类相关知识学习
    创建文件夹
String folderPath = "D:\\eclipse\\CXY\\newfolder";
               createfolder(folderPath);
public static void createfolder(String folderPath) {
        File file = new File(folderPath);
        file.mkdirs();//  创建此抽象路径名指定的目录,包括所有必需但不存在的父目录
    }

创建文件

String longFileName = newFolderPath+"\\file.txt";
        createFile(longFileName);
    public static boolean createFile(String fileName) {
        File file = new File(fileName);
        System.out.println(file.getAbsolutePath());// file.getAbsolute()返回此抽象路径名的绝对路径名字符串
        boolean isSuccess = false;
        try {
            isSuccess = file.createNewFile();//方法自动创建此抽象路径名的新文件,当文件不存在,创建文件,返回true,文件存在,则返回false
        } catch (IOException e) {
            e.printStackTrace();
        }
        return isSuccess;
    }

遍历文件夹下的文件

  listFiles(folderPath);
    public static void listFiles(String folderPath) {
        File file = new File(folderPath);
        for(String str :file.list()){
                    System.out.println(str);
        }  
    }

写入文件

writeToFile(longFileName);
    public static void writeToFile(String fileName){
        File file =new File(fileName);
        BufferedWriter bWrite =null;
        
        try {
            FileWriter writer =new FileWriter(file);//FileWriter 用于写入字符流,根据给定的文件名构造一个 FileWriter 对象。 
            bWrite =new BufferedWriter(writer);//BufferedWriter 将文本写入字符输出流,缓冲各个字符,从而提供单个字符、数组和字符串的高效写入
            bWrite.write("孔内吉娃");
            bWrite.newLine();
            bWrite.write("刷我滴卡");
            bWrite.newLine();
            bWrite.write("你好"); 
            System.out.println("写入成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(bWrite !=null){
                try {
                    bWrite.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

读取文件

readeToFile(longFileName);
    public static void readeToFile(String fileName) {
        File file = new File(fileName);
        BufferedReader bReade = null;

        try {
            FileReader reade = new FileReader(fileName);//FileReader 用于读取字符流,在给定从中读取数据的 fileName 的情况下创建一个新 FileReader
            bReade = new BufferedReader(reade);//BufferedReader 从字符输入流中读取文本,缓冲各个字符,从而实现字符、数组和行的高效读取
            String line = bReade.readLine();
            while (line != null) {
                System.out.println(line);

                line = bReade.readLine();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

你可能感兴趣的:(java day 17)