Difference between methods of creating files in java
区别:
mkdir
和mkdirs
: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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Chinese version
Chinese version, very easy to use
