Home  >  Article  >  Java  >  Difference between methods of creating files in java

Difference between methods of creating files in java

王林
王林forward
2019-11-28 13:57:431804browse

Difference between methods of creating files in java

区别:

mkdirmkdirs:mkdir只能用来创建文件夹,且只能创建一级目录;

mkdirs同样只能用来创建文件夹,可创建多级目录 ,如果上级不存在,就会自动创建。

createNewFile:只能用来创建文件,且只能在已存在的目录下创建文件。

一般情况下配合使用,附上一段代码,会在自定义的目录下创建名为111的docx文件,将inputString字符串内容写入其中。

想学习java么,这里有免费视频教程:java教学视频

示例演示如下:

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class Modify {

    public static void main(String[] args) throws IOException {
        String path = "F:\\Users\\yyy\\Desktop\\111.docx";
        Modify modify = new Modify();
        modify.create("hhh",path);
    }

    /**
     *
     * @param inputString 需写入的字符串内容
     * @param path 文件创建的路径
     * @throws IOException
     */
    private void create(String inputString,String path) throws IOException {
        String newPath = path.substring(0,path.lastIndexOf("\\"));
        File file = new File(newPath);
        if (!file.exists()){
            file.mkdirs();
        }
        File newFile = new File(path);
        if (!newFile.exists()){
            newFile.createNewFile();
        }
        ByteArrayInputStream input = new ByteArrayInputStream(inputString.getBytes());
        int index;
        byte[] bytes = new byte[1024];
        FileOutputStream fs = new FileOutputStream(path);
        while ((index = input.read(bytes)) != -1) {
            fs.write(bytes, 0, index);
            fs.flush();
        }
        fs.close();
        input.close();
    }
}

大家都在查看的教程:java编程入门

The above is the detailed content of Difference between methods of creating files in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete