Home > Java > Javagetting Started > Difference between methods of creating files in java

Difference between methods of creating files in java

王林
Release: 2019-11-28 13:57:43
forward
2001 people have browsed it

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();
    }
}
Copy after login

大家都在查看的教程: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!

source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template