java中如何在目录下创建文件?

问题描述 投票:0回答:13

如果我想在

C:/a/b/test.txt
中创建文件,我可以这样做吗:

File f = new File("C:/a/b/test.txt");

另外,我想使用

FileOutputStream
来创建文件。那么我该怎么做呢?由于某种原因,该文件没有在正确的目录中创建。

java file-io
13个回答
272
投票

最好的方法是:

String path = "C:" + File.separator + "hello" + File.separator + "hi.txt";
// Use relative path for Unix systems
File f = new File(path);

f.getParentFile().mkdirs(); 
f.createNewFile();

53
投票

写入前需要确保父目录存在。您可以通过

File#mkdirs()
来做到这一点。

File f = new File("C:/a/b/test.txt");
f.getParentFile().mkdirs();
// ...

48
投票

NIO.2

通过 Java 7 中的 NIO.2,您可以使用

Path
Paths
Files
:

import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class CreateFile {

    public static void main(String[] args) throws IOException {
        Path path = Paths.get("/tmp/foo/bar.txt");

        Files.createDirectories(path.getParent());

        try {
            Files.createFile(path);
        } catch (FileAlreadyExistsException e) {
            System.err.println("already exists: " + e.getMessage());
        }
    }
}

14
投票

用途:

File f = new File("C:\\a\\b\\test.txt");
f.mkdirs();
f.createNewFile();

请注意,我将 Windows 文件系统中的路径的正斜杠更改为双反斜杠。这将在给定路径上创建一个空文件。


3
投票
String path = "C:"+File.separator+"hello";
String fname= path+File.separator+"abc.txt";
    File f = new File(path);
    File f1 = new File(fname);

    f.mkdirs() ;
    try {
        f1.createNewFile();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

这应该在目录中创建一个新文件


2
投票

更好更简单的方法:

File f = new File("C:/a/b/test.txt");
if(!f.exists()){
   f.createNewFile();
}

来源


2
投票

令人惊讶的是,许多答案都没有给出完整的工作代码。这是:

public static void createFile(String fullPath) throws IOException {
    File file = new File(fullPath);
    file.getParentFile().mkdirs();
    file.createNewFile();
}

public static void main(String [] args) throws Exception {
    String path = "C:/donkey/bray.txt";
    createFile(path);
}

1
投票

在指定路径创建新文件

import java.io.File;
import java.io.IOException;

public class CreateNewFile {

    public static void main(String[] args) {
        try {
            File file = new File("d:/sampleFile.txt");
            if(file.createNewFile())
                System.out.println("File creation successfull");
            else
                System.out.println("Error while creating File, file already exists in specified path");
        }
        catch(IOException io) {
            io.printStackTrace();
        }
    }

}

程序输出:

文件创建成功


1
投票

创建一个文件并在其中写入一些字符串:

BufferedWriter bufferedWriter = Files.newBufferedWriter(Paths.get("Path to your file"));
bufferedWriter.write("Some string"); // to write some data
// bufferedWriter.write("");         // for empty file
bufferedWriter.close();

这适用于 Mac 和 PC。


0
投票

要使用 FileOutputStream,请尝试以下操作:

public class Main01{
    public static void main(String[] args) throws FileNotFoundException{
        FileOutputStream f = new FileOutputStream("file.txt");
        PrintStream p = new PrintStream(f);
        p.println("George.........");
        p.println("Alain..........");
        p.println("Gerard.........");
        p.close();
        f.close();
    }
}

0
投票

当您通过文件输出流写入文件时,将自动创建该文件。但请确保创建了所有必要的目录(文件夹)。

    String absolutePath = ...
    try{
       File file = new File(absolutePath);
       file.mkdirs() ;
       //all parent folders are created
       //now the file will be created when you start writing to it via FileOutputStream.
      }catch (Exception e){
        System.out.println("Error : "+ e.getmessage());
       }

0
投票

我在这里解决同样的问题,我终于解决了。

目标是在文件夹中创建一个文件(例如 .txt 文件)。

你需要的东西:

  1. 文件夹名称

而不是这个:

File f = new File("C:/a/b/test.txt");

尝试

//get the file's absolute path. You could input it yourself
// but I think it is better to have a function to handle
// system rules on how to format the path string

String myFolder = "b";
String myFile = "test.txt";
String folderPath = myFolder.getAbsolutePath(); //will get the entire path for you

String pathToFile = folderPath + File.separator + myFile;

// this will probably throw a exception, you want to make sure you handle it
try {
    File newFile = new File(pathToFile);
    if (newFile.createNewFile()) {    
         System.out.println("bwahahah success");
    }
    else {
        System.out.println("file creation failed");
    }
}catch(IOException e) {
    System.out.println(e.getMessage());   // you will need to print the message in order to get some insight on what the problem is.
}

// you can also add a throw if within the if statement with other checks in order to know where the error is coming from, but to keep it short this is the gist of it.

// Really hope this will assist anyone that stumbles upon this same issue.

其他供进一步阅读的资源:有关 java 路径和文件的所有内容

如果有什么我可能忽略的地方请评论,让我吸收一些知识


0
投票

只是将一些答案结合在一起。

import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

class Scratch {
    public static void main(String[] args) {

        String fileTargetLocation = "C:\\testing\\";
        String fileNameAndExtension = "test.txt";

        boolean fileCreated = createFile(fileTargetLocation, fileNameAndExtension);
        if (fileCreated) {
            String stringForFile = "This is some test text to write into the file.";
            writeIntoFile(fileTargetLocation, fileNameAndExtension, stringForFile);
        }
    }

    /**
     * Attempts to create a file at the given location, with the given file name and desired extension.
     *
     * @param fullPath             full path to folder in which the file needs to be created, example: C:\testing\
     *                             (ending with a foreword slash)
     * @param fileNameAndExtension file name and desired extension. Example: environment.properties, test.txt
     * @return successful file creation boolean
     */
    public static boolean createFile(String fullPath, String fileNameAndExtension) {
        try {
            return new File(fullPath + fileNameAndExtension).createNewFile();
        } catch (IOException io) {
            io.printStackTrace();
        }
        return false;
    }

    /**
     * Attempt to write into the given file.
     *
     * @param fullPath             full path to folder in which the file needs to be created, example: C:\testing\
     *                             (ending with a foreword slash)
     * @param fileNameAndExtension file name and extension. Example: environment.properties, test.txt
     * @param whatToWriteToFile    string to write to the file
     */
    public static void writeIntoFile(String fullPath, String fileNameAndExtension, String whatToWriteToFile) {
        try (BufferedWriter bufferedWriter = Files.newBufferedWriter(Paths.get(fullPath + fileNameAndExtension))) {
            bufferedWriter.write(whatToWriteToFile);
        } catch (IOException io) {
            io.printStackTrace();
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.