java 'File' Object not making the directory and file - java

I was trying to make a directory and file using java with File object as:
import java.io.*;
class CreateFile{
public static void main(String[] args) throws IOException{
File f = new File("File/handling/file1.txt");
if(!f.exists())
f.createNewFile();
}
}
but its showing error (see below) and unable to make it, the path and file name doesn't existed before execution. I don't know where am I going wrong, someone please clarify whats the mistake and how to resolve it? It might be I need to know something about File object, so please do tell me...
See error:
Exception in thread "main" java.io.IOException: The system cannot find the path
specified
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:947)
at CreateFile.main(CreateFile.java:6)

The error is telling you that either there is no File directory relative to where you're running this, or there is but it doesn't have a handling subdirectory. In this case, exists returns false and so you call createNewFile to try to create the file, but the directory in which you're trying to create it doesn't exist, and so it throws an exception.
You can use mkdirs to create the directories if necessary, like so:
import java.io.*;
class CreateFile{
public static void main(String[] args) throws IOException{
File f = new File("File/handling/file1.txt");
if(!f.exists()) {
f.getParentFile().mkdirs(); // This is a no-op if it exists
f.createNewFile();
}
}
}

Related

FileReader can't find file despite file existing

I am trying to use the opencsv library however I am getting stuck early on with FileReader not being able to find the csv I am using to test with.
I have the following code:
import java.io.File;
import java.io.FileReader;
public class Test {
public static void main(String[] args) {
File f = new File("demo.csv");
if(f.exists() && !f.isDirectory()) {
System.out.println("File exists");
}
else {
System.out.println("File does not exist");
}
FileReader reader = new FileReader("demo.csv");
}
}
I am getting a FileNotFoundException error on the FileReader:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type FileNotFoundException at Test.main(Test.java:19)
despite having checked the file exists in the correct directory using f.exist. Done a load of searching and found nothing to explain it.
Can anyone help with this?
check if the file extension is visible and your file is not named demo.csv.csv. Happend to me and took me a while to resolve.
By default, the compiler would look for "demo.csv" in the root directory. Make sure that you clearly specify the path in FileReader parameter.
The same code does work in my case (provided demo.csv in right under the root directory)

File default location

Why the program search the file:
File FILE_PATH = new File("‪‪C:\\Users\\home\\Desktop\\DbWord.txt");
System.out.println(FILE_PATH.exists());
System.out.println(FILE_PATH.getAbsoluteFile());
FileInputStream fIn = new FileInputStream(FILE_PATH);
Scanner reader = new Scanner(fIn);
at: C:\Users\home\Documents\NetBeansProjects\MyDatabase\‪‪C:\Users\home\Desktop\DbWord.txt
How can i counteract the default location?
If something in this post not good, please tell me and no negative vote.
Thanks!
why negative votes??????????????? whats your problems??????????
Please double check your error details. You might have seen something like the below error. Actually the program is not searching for the file "C:\Users\home\Documents\NetBeansProjects\MyDatabase\‪‪C:\Users\home\Desktop\DbWord.txt", it is trying to locate the file "C:\Users\home\Desktop\DbWord.txt" which does not exists in your machine. You are seeing "C:\Users\home\Documents\NetBeansProjects\MyDatabase\‪‪C:\Users\home\Desktop\DbWord.txt" along with the error because you have already used System.out.println(FILE_PATH.getAbsoluteFile()); statement in your code.
false
Exception in thread "main" java.io.FileNotFoundException: ‪‪C:\Users\home\Desktop\DbWord.txt (The filename, directory name, or volume label syntax is incorrect)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
C:\Users\home\Documents\NetBeansProjects\MyDatabase\‪‪C:\Users\home\Desktop\DbWord.txt
at com.stackoverflow.answer.SimpleFileHelper.main(SimpleFileHelper.java:17)
Hope you are clear now.
There are three main chances where a FileNotFoundException may be thrown.
The named file does not exist.
The named file is actually a directory not file.
The named file cannot be opened for reading due to some reason.
The first two reasons are unlikely based on your description, please check the third point using file.canRead() method.
If the test above returns true, I would suspect the following:
You might have forgotten to explicitly throw or catch the potential exception (i.e., FileNotFoundExcetion). If you work in an IDE, you should have got some complaint from the compiler. But I suspect you didn't run your code in such an IDE.
Try the following code and see if the exception would be gone:
package com.stackoverflow.answer;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class SimpleFileHelper {
public static void main(String[] args) throws FileNotFoundException {
File FILE_PATH = new File("C:/Users/home/Desktop/DbWord.txt");
System.out.println(FILE_PATH.exists());
System.out.println(FILE_PATH.getAbsoluteFile());
FileInputStream fIn = new FileInputStream(FILE_PATH);
Scanner reader = new Scanner(fIn);
}
}

what is in java importing packages

import java.io.*;
public class createfile{
public static void main(String args[]) throws IOException{
File f=new File("javafile.txt");
if(f.exists())
{
f.createNewFile();
System.out.println("New file \"javafile.txt\"has been created to the current directory");
}
else
System.out.println("The specified file is already exist");
}
}
I created a existing file "javafile.txt". i entered some text into this.. If i compile javac, i hope that file must be recreated by the following codes
if(f.exists())
{
f.createNewFile();
}
but it didn't create.. when i open it, the existing file opens. why?
File.createNewFile() create new file if not exists already.
public boolean createNewFile() throws IOException
Atomically creates a new, empty file named by this abstract pathname if and only if a file with
this name does not yet exist. The check for the existence of the file
and the creation of the file if it does not exist are a single
operation that is atomic with respect to all other filesystem
activities that might affect the file.
From the documentation (emphasis mine):
Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist.
This is exactly how the method is supposed to work.

Program that cannot acess input from a file

I have a program that scans a file and then closes the file.
import java.util.*;
import java.io.*;
public class FileTester{
public static void main(String[] args) throws IOException {
File test = new File("MyDatta.in.txt");
Scanner sf = new Scanner(test);
sf.close();
}
}
When I run the program I get an error message like this:
Exception in thread "main" java.io.FileNotFoundException: MyDatta.in.txt (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:120)
at java.util.Scanner.<init>(Scanner.java:636)
at FileTester.main(FileTester.java:6)
I have a mac that runs on Mac OS. I have reason to believe it has to do with the pathway to my file which is in documents. I know in windows one would use C:\folder name\file to scan it but I just don't know with Mac and I cannot find it anywhere
From Java documentation for FileInputStream: "If the named file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading then a FileNotFoundException is thrown."
Maybe file is used by another program?
You should put this as the file path:
~/Documents/MyDatta.in.txt
to tell java that your file is in documents. The ~ is your home folder.

Passing in a file name / directory into command line in Java

I'm trying to do some processing on whether the user enters a (1) file name, or (2) directory name into the command line. Anything else should throw an error. Starting with the simplest case, I wrote this:
import java.io.*;
import java.util.*;
public class RemoveDuplicates {
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Program accepts one command-line argument. Exiting!");
System.exit(1);
}
File f = new File(args[0]);
if (f.isDirectory()) {
System.out.println("is directory");
}
else if (f.isFile()) {
System.out.println("is file");
}
else {
System.out.println("Shouldn't happen");
}
}
}
at the command line, I type: java RemoveDuplicates example.txt
and I get the reuslts, "Shouldn't happen." I also tried java RemoveDuplicates "example.txt" and that doesn't work either. So I was wondering if my code is wrong, or how I'm passing it into the command line is wrong for starters.
Secondly, how do you pass in a directory name? Like if your directory was myDirectory, is it the same thing: java RemoveDuplicates myDirectory
Third, why if I put my File f = new File(args[0]) into a try block and have a catch block, I get a compile error about what is in my try block never throws an exception. I thought File threw an exception? Thanks in advance!
Are you sure example.txt exists in your working directory? Try adding the following and see what happens.
File f = new File(args[0]);
if (!f.exists()) {
System.out.println("does not exist");
}
You have that right.
Actually, I don't get this error. How did you do the try/catch?
So I was wondering if my code is wrong, or how I'm passing it into the command line is
wrong for starters
Is that file present in your working directory? Something which doesn't exist is neither a file nor a directory. Try creating a sample text file with the same name and then invoking your program.
how do you pass in a directory name
Pass in a fully qualified string which represents your directory (e.g. java MyProg "c:\testdir\mydir") pass in a directory path relative to your current working directory (e.g. java MyProg testdir/mydir)
File f = new File(args[0]). I thought File threw an exception?
Creating a new File object doesn't create a physical file hence no IOException is thrown as you expected. It is only when you try to open a file for reading or writing a FileNotFoundException is thrown. Hence it's a good practice to always check for the existence of a File before using it for IO.
I compiled & ran your program. It is working as expected.
C:\upul\eclipse\src\Test\src>java RemoveDuplicates RemoveDuplicates.java
is file
C:\upul\eclipse\src\Test\src>java RemoveDuplicates c:\upul
is directory
You need to type java RemoveDuplicates.java example.txt.
Correct.
You should be able to do that as anything can throw RuntimeException which is a subclass of Exception.

Categories