How to create a file in a directory in java?

JavaFile Io

Java Problem Overview


If I want to create a file in C:/a/b/test.txt, can I do something like:

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

Also, I want to use FileOutputStream to create the file. So how would I do it? For some reason the file doesn't get created in the right directory.

Java Solutions


Solution 1 - Java

The best way to do it is:

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();

Solution 2 - Java

You need to ensure that the parent directories exist before writing. You can do this by File#mkdirs().

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

Solution 3 - Java

With Java 7, you can use Path, Paths, and 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());
        }
    }
}

Solution 4 - Java

Use:

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

Notice I changed the forward slashes to double back slashes for paths in Windows File System. This will create an empty file on the given path.

Solution 5 - Java

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

This should create a new file inside a directory

Solution 6 - Java

A better and simpler way to do that :

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

Source

Solution 7 - Java

Create New File in Specified Path

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

}

Program Output:

File creation successfull

Solution 8 - Java

Surprisingly, many of the answers don't give complete working code. Here it is:

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);
}

Solution 9 - Java

To create a file and write some string there:

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();

This works for Mac and PC.

Solution 10 - Java

For using the FileOutputStream try this :

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

Solution 11 - Java

When you write to the file via file output stream, the file will be created automatically. but make sure all necessary directories ( folders) are created.

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

Solution 12 - Java

In java we can create file using various predefined method .Let's discuss about these method one by one

Method 1 : Create File with java.io.File class

We can create file using createNewFile() method of File class

public class CreateFileJavaExamples {
	public static void main(String[] args) {
		File file = new File("C://java_//newFile.txt");
		try {
			if (file.createNewFile()) {
				System.out.println("File create");
			} else {
				System.out.println("File already exists!");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

Method 2 : Create File Using java.io.FileOutputStream

In this example we can create file using FileOutputStream

public class CreateFileJavaExamples2 {
	
	public static void main(String[] args) {
		 try {
	            new FileOutputStream("C://java_examples//newFile1.txt", true);
	            System.out.println("file created successfully");
	        } catch (Exception e) {
	        	e.printStackTrace();
	        }
	}
}

We can also create file with java.nio Package .

Source : How to Create File In Java

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionUereferView Question on Stackoverflow
Solution 1 - JavaRMTView Answer on Stackoverflow
Solution 2 - JavaBalusCView Answer on Stackoverflow
Solution 3 - Javauser1907906View Answer on Stackoverflow
Solution 4 - JavaMarceloView Answer on Stackoverflow
Solution 5 - JavaChittaView Answer on Stackoverflow
Solution 6 - JavaMehdiView Answer on Stackoverflow
Solution 7 - JavaAKHYView Answer on Stackoverflow
Solution 8 - JavaMasterJoeView Answer on Stackoverflow
Solution 9 - JavaKirill ChView Answer on Stackoverflow
Solution 10 - JavaFridjato Part FridjatView Answer on Stackoverflow
Solution 11 - JavaTomView Answer on Stackoverflow
Solution 12 - Javaphp kingView Answer on Stackoverflow