区别:
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编程入门
以上就是java中创建文件的方法之间的区别的详细内容。