博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java创建新文件_Java创建新文件
阅读量:2532 次
发布时间:2019-05-11

本文共 6799 字,大约阅读时间需要 22 分钟。

java创建新文件

Creating a file is a very common IO operation. Today we will look into different ways to create a file in java.

创建文件是非常常见的IO操作。 今天,我们将探讨在Java中创建文件的不同方法。

Java创建文件 (Java create file)

There are three popular methods to create file in java. Let’s look at them one by one.

有三种在Java中创建文件的流行方法。 让我们一一看一下。

  1. File.createNewFile() (File.createNewFile())

    java.io.File class can be used to create a new File in Java. When we initialize File object, we provide the file name and then we can call createNewFile() method to create new file in Java.

    File createNewFile() method returns true if new file is created and false if file already exists. This method also throws java.io.IOException when it’s not able to create the file. The files created is empty and of zero bytes.

    When we create the File object by passing the file name, it can be with absolute path, or we can only provide the file name or we can provide the relative path.

    For a non-absolute path, File object tries to locate files in the project root directory. If we run the program from command line, for the non-absolute path, File object tries to locate files from the current directory.

    While creating the file path, we should use System property file.separator to make our program platform independent.

    Let’s see different scenarios with a simple java program to create a new file in java.

    package com.journaldev.files;import java.io.File;import java.io.IOException;public class CreateNewFile {    /**     * This class shows how to create a File in Java     * @param args     * @throws IOException      */    public static void main(String[] args) throws IOException {        String fileSeparator = System.getProperty("file.separator");                //absolute file name with path        String absoluteFilePath = fileSeparator+"Users"+fileSeparator+"pankaj"+fileSeparator+"file.txt";        File file = new File(absoluteFilePath);        if(file.createNewFile()){            System.out.println(absoluteFilePath+" File Created");        }else System.out.println("File "+absoluteFilePath+" already exists");                //file name only        file = new File("file.txt");        if(file.createNewFile()){            System.out.println("file.txt File Created in Project root directory");        }else System.out.println("File file.txt already exists in the project root directory");                //relative path        String relativePath = "tmp"+fileSeparator+"file.txt";        file = new File(relativePath);        if(file.createNewFile()){            System.out.println(relativePath+" File Created in Project root directory");        }else System.out.println("File "+relativePath+" already exists in the project root directory");    }}

    When we execute the above program from Eclipse IDE for the first time, the below output is produced.

    For the relative path, it throws IOException because tmp directory is not present in the project root folder.

    So it’s clear that createNewFile() just tries to create the file and any directory either absolute or relative should be present already, else it throws IOException.

    So I created “tmp” directory in the project root and executed the program again, here is the output.

    File /Users/pankaj/file.txt already existsFile file.txt already exists in the project root directorytmp/file.txt File Created in Project root directory

    First two files were already present, so createNewFile() returns false, third file was created in tmp directory and returns true.

    Any subsequent execution results in the following output:

    If you run the same program from terminal classes directory, here is the output.

    //first execution from classes output directory	pankaj:~/CODE/JavaFiles/bin$ java com/journaldev/files/CreateNewFileFile /Users/pankaj/file.txt already existsfile.txt File Created in Project root directoryException in thread "main" java.io.IOException: No such file or directory	at java.io.UnixFileSystem.createFileExclusively(Native Method)	at java.io.File.createNewFile(File.java:947)	at com.journaldev.files.CreateNewFile.main(CreateNewFile.java:32)//tmp directory doesn't exist, let's create itpankaj:~/CODE/JavaFiles/bin$ mkdir tmp//second time executionpankaj:~/CODE/JavaFiles/bin$ java com/journaldev/files/CreateNewFileFile /Users/pankaj/file.txt already existsFile file.txt already exists in the project root directorytmp/file.txt File Created in Project root directory//third and subsequent executionpankaj:~/CODE/JavaFiles/bin$ java com/journaldev/files/CreateNewFileFile /Users/pankaj/file.txt already existsFile file.txt already exists in project root directoryFile tmp/file.txt already exists in project root directory

    java.io.File类可用于在Java中创建新的File。 初始化File对象时,我们提供文件名,然后可以调用createNewFile()方法来用Java创建新文件。

    如果创建了新文件,则文件createNewFile()方法返回true ,如果文件已经存在,则返回false 。 当无法创建文件时,此方法还会引发java.io.IOException 。 创建的文件为空,且为零字节。

    当我们通过传递文件名来创建File对象时,它可以使用绝对路径 ,也可以仅提供文件名,也可以提供相对路径。

    对于非绝对路径,File对象尝试在项目根目录中找到文件。 如果我们从命令行运行程序,对于非绝对路径,File对象将尝试从当前目录中查找文件。

    创建文件路径时,我们应使用系统属性file.separator使程序平台独立。

    让我们看看用一个简单的Java程序在Java中创建一个新文件的不同场景。

    当我们第一次从Eclipse IDE执行上述程序时,将产生以下输出。

    /Users/pankaj/file.txt File Createdfile.txt File Created in Project root directoryException in thread "main" java.io.IOException: No such file or directory	at java.io.UnixFileSystem.createFileExclusively(Native Method)	at java.io.File.createNewFile(File.java:947)	at com.journaldev.files.CreateNewFile.main(CreateNewFile.java:32)

    对于相对路径,它会引发IOException,因为项目根文件夹中没有tmp目录。

    因此很明显, createNewFile()只是尝试创建文件,并且绝对目录或相对目录都应该已经存在,否则会抛出IOException

    因此,我在项目根目录中创建了“ tmp”目录,并再次执行了程序,这是输出。

    前两个文件已经存在,因此createNewFile()返回false ,第三个文件在tmp目录中创建并返回true

    任何后续执行将导致以下输出:

    File /Users/pankaj/file.txt already existsFile file.txt already exists in the project root directoryFile tmp/file.txt already exists in the project root directory

    如果从终端类目录运行相同的程序,则输出为。

  2. FileOutputStream.write(byte [] b) (FileOutputStream.write(byte[] b))

    If you want to create a new file and at the same time write some data into it, you can use write method. Below is a simple code snippet to show it’s usage. The rules for absolute path and relative path discussed above is applicable in this case too.

    String fileData = "Pankaj Kumar";FileOutputStream fos = new FileOutputStream("name.txt");fos.write(fileData.getBytes());fos.flush();fos.close();

    如果要创建一个新文件并同时向其中写入一些数据,则可以使用写入方法。 以下是显示其用法的简单代码段。 上面讨论的绝对路径和相对路径的规则也适用于这种情况。

  3. Java NIO Files.write() (Java NIO Files.write())

    We can use class to create a new file and write some data into it. This is a good option because we don’t have to worry about closing IO resources.

    String fileData = "Pankaj Kumar";Files.write(Paths.get("name.txt"), fileData.getBytes());

    我们可以使用类创建一个新文件并将一些数据写入其中。 这是一个不错的选择,因为我们不必担心关闭IO资源。

That’s all for creating a new file in the java program.

这就是在java程序中创建新文件的全部。

. 检出更多核心Java示例。

翻译自:

java创建新文件

转载地址:http://tmozd.baihongyu.com/

你可能感兴趣的文章
小D课堂 - 零基础入门SpringBoot2.X到实战_第14节 高级篇幅之SpringBoot多环境配置_59、SpringBoot多环境配置介绍和项目实战...
查看>>
小D课堂 - 零基础入门SpringBoot2.X到实战_第10节 SpringBoot整合定时任务和异步任务处理_41、SpringBoot定时任务schedule讲解...
查看>>
小D课堂 - 零基础入门SpringBoot2.X到实战_第10节 SpringBoot整合定时任务和异步任务处理_43、SpringBoot2.x异步任务实战(核心知识)...
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_1_01课程简介
查看>>
小D课堂 - 零基础入门SpringBoot2.X到实战_第11节 Logback日志框架介绍和SpringBoot整合实战_45、SpringBoot2.x日志讲解和Logback配置实战...
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_1_02技术选型
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_汇总
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_2_01传统架构演进到分布式架构
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_2_02 微服务核心基础讲解
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_2_04微服务下电商项目基础模块设计...
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_3-01 什么是微服务的注册中心
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_3-03CAP原理、常见面试题
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_3-04 SpringCloud微服务核心组件Eureka介绍和闭源后影响...
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_3-05 服务注册和发现Eureka Server搭建实战...
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_3-06 服务注册和发现之Eureka Client搭建商品服务实战...
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_3-07 Eureka服务注册中心配置控制台问题处理...
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_4-01 常用的服务间调用方式讲解
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_4-02 微服务调用方式之ribbon实战 订单调用商品服务...
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_4-03 高级篇幅之Ribbon负载均衡源码分析实战...
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_4-06 Feign核心源码解读和服务调用方式ribbon和Feign选择...
查看>>