How to create a file in a directory in java? - java

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.

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

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

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

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.

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

A better and simpler way to do that :
File f = new File("C:/a/b/test.txt");
if(!f.exists()){
f.createNewFile();
}
Source

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

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

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.

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

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

Related

How do I write to a File stored in a path in Java

I have a Path variable like this:
Path output;
This path is initialized in the main-method.
I want to check if there exists a File in this path
and if thats the case- write a string into that file.
Else create a new File with the given path and write
the string.
//void parseOutput(String s){
//if (file in path exists)
// write(s in file from path)
else
File f = new File(String.valueOf(output));
write String in f
You can try this :
import java.io.*;
class FileDemo {
public static void main(String str[]) {
String path = "E:/myfile.txt";
File file = new File(path);
if(file.exists()) {
System.out.println("File is exist..!!!");
} else {
try {
FileWriter fileWriter = new FileWriter(path);
fileWriter.write("This is my first file..!!");
fileWriter.close();
System.out.println("File has some content..!!");
} catch(Exception exception) {
System.out.println(exception.getMessage());
}
}
}
}
If you have a Path, it doesn't really make sense to convert that to a String and use the File constructor.
For checking if a file exists, you can use Files exists.
To add to an existing file, have a look at Files.newBufferedWriter with the APPEND OpenOption set.
Full example:
Path path = Paths.get("/path/to/file.txt");
try (BufferedWriter bufferedWriter = Files.newBufferedWriter(
path, StandardOpenOption.APPEND, StandardOpenOption.CREATE);
PrintWriter printWriter = new PrintWriter(bufferedWriter))
{
printWriter.println("This is a line");
}
You might want to use exists() method in File class. Here's an example which you could use:
public void writeOnFile(String path, String str) throws FileNotFoundException {
PrintWriter out;
File file = new File(path);
if (file.exists()){
out = new PrintWriter(file.getPath());
out.println(str);
}
}

Text document is becoming file folder

Here is my class, what I am doing wrong. Why is my text document becoming a file folder. Please explain what is going on and how I can correct it. Thank you
public class InputOutput {
public static void main(String[] args) {
File file = new File("C:/Users/CrypticDev/Desktop/File/Text.txt");
Scanner input = null;
if (file.exists()) {
try {
PrintWriter pw = new PrintWriter(file);
pw.println("Some data that we have stored");
pw.println("Another data that we stored");
pw.close();
} catch(FileNotFoundException e) {
System.out.println("Error " + e.toString());
}
} else {
file.mkdirs();
}
try {
input = new Scanner(file);
while(input.hasNext()) {
System.out.println(input.nextLine());
}
} catch(FileNotFoundException e) {
System.out.println("Error " + e.toString());
} finally {
if (input != null) {
input.close();
}
}
System.out.println(file.exists());
System.out.println(file.length());
System.out.println(file.canRead());
System.out.println(file.canWrite());
System.out.println(file.isFile());
System.out.println(file.isDirectory());
}
}
Thanks. The above is my Java class.
You mistakingly assume Text.txt is not a directory name.
mkdirs() creates a directory (and all directories needed to create it). In your case 'Text.txt'
See here: https://docs.oracle.com/javase/7/docs/api/java/io/File.html#mkdirs().
It is perfectly fine for a directory to have a . in it.
You could use getParentFile() to get the directory you want to create and use mkdirs() on that.
For additional informations. Here is the différence between the two representaions of files and directories:
final File file1 = new File("H:/Test/Text.txt"); // Creates NO File/Directory
file1.mkdirs(); // Creates directory named "Text.txt" and its parent directory "H:/Test" if it doesn't exist (may fail regarding to permissions on folders).
final File file = new File("H:/Test2/Text.txt"); // Creates NO File/Directory
try {
file.createNewFile(); // Creates file named "Text.txt" (if doesn't exist) in the folder "H:/Test2". If parents don't exist, no file is created.
} catch (IOException e) {
e.printStackTrace();
}
Replace your code:
else {
file.mkdirs();
}
with:
else {
if (!file.isFile()&&file.getParentFile().mkdirs()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}

why is this file empty? this code should populate it with stuff

package stuff;
import java.io.IOException;
public class DataWriter {
public static void main(String[] args) throws IOException {
java.io.File file = new java.io.File("mydata.txt");
if (file.exists()) {
System.out.println("file already exists");
System.exit(1);
}
java.io.PrintWriter output = new java.io.PrintWriter(file);
output.println("data1");
output.println("data2"");
output.println("data3");
output.println("data4");
output.println("data5");
output.println("data6");
output.println(" data7");
System.out.println("data8");
}
}
This code creates a "mydata.txt" but does not populate it with anything. Why isn't this working? I've been trying to get this work for 3 weeks!
your not closing the output variable
java.io.File file = new java.io.File("mydata.txt");
if(file.exists()) {
System.out.println("file already exists");
System.exit(1);
}
java.io.PrintWriter output = new java.io.PrintWriter(file);
output.println("data1");
output.println("data2");
output.println("data3");
output.println("data4");
output.println("data5");
output.println("data6");
output.println(" data7");
output.close(); //close<--------------------------------
System.out.println("data8");
You need to close the file with:
output.close();

Where do i have to put input file in eclipse(java) in order to write into it

I am trying to enter data into a text file from a java program. The program is executing and showing the output as success but when i open the text file it is still blank.
Here is my code
package com.example.ex2;
import java.io.*;
class Input{
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("abc.txt");
String s="Good MOrning";
byte b[]=s.getBytes();
fout.write(b);
fout.close();
System.out.println("success...");
}catch(Exception e){
System.out.println(e);}
}
}
I think i have gone wrong in placing the text file. I have placed it in the default directory.
Your code works fine. Check the correct file.
If you are running from IDE, it will be in the current working directory.
It is always better to your a temp or directory to store files ( certainly not in working dir)
Here is a best practice code. You can tune it further if you wish
public static void main(String args[])
{
FileOutputStream fout = null;
try
{
File f = new File("abc.txt");
if (!f.isFile())
f.createNewFile();
fout = new FileOutputStream(f);
String s = "Good MOrning";
byte b[] = s.getBytes();
fout.write(b);
System.out.println("success... printed at : " + f.getAbsolutePath());
} catch (Exception e)
{
System.out.println(e);
} finally
{
if (null != fout)
try
{
fout.close();
} catch (IOException e)
{
}
}
}

File.mkdirs() creating a directory instead of a file

I am trying to serialize the following class:
public class Library extends ArrayList<Book> implements Serializable{
public Library(){
check();
}
using the following method of that class:
void save() throws IOException {
String path = System.getProperty("user.home");
File f = new File(path + "\\Documents\\CardCat\\library.ser");
ObjectOutputStream oos = new ObjectOutputStream (new FileOutputStream (f));
oos.writeObject(this);
oos.close();
}
However, rather than creating a file called library.ser, the program is creating a directory named library.ser with nothing in it. Why is this?
If its helpful, the save() method is initially called from this method (of the same class):
void checkFile() {
String path = System.getProperty("user.home");
File f = new File(path + "\\Documents\\CardCat\\library.ser");
try {
if (f.exists()){
load(f);
}
else if (!f.exists()){
f.mkdirs();
save();
}
} catch (IOException | ClassNotFoundException ex) {
Logger.getLogger(Library.class.getName()).log(Level.SEVERE, null, ex);
}
}
File.mkdirs() creating a directory instead of a file
That's what it's supposed to do. Read the Javadoc. Nothing there about creating a file.
f.mkdirs();
It is this line that creates the directory. It should be
f.getParentFile().mkdirs();
I'm pretty sure that the call to f.mkdirs() is your problem. If the file doesn't already exist (which seems to be your case), the f.mkdirs() call will give you a directory called "library.ser" instead of a File, which is why your "save()" call isn't working - you can't serialize an object to a directory.

Categories