Why the file is not created - java

I'm creating a directory and then a file. The problem is that the directory is created but the File is not.
When I'm doing this I'm creating and it prints out that "Successfully created new file: and the name of the file.
Can anyone help understand why?
public class Main
{
public static void main(String[] args) throws IOException
{
Scanner reader = new Scanner (System.in);
boolean success = false;
GetFiles getFile = new GetFiles();
System.out.println("Enter path of directory to create");
String dir = reader.nextLine();
// Create a new directory in Java, if it doesn't exists
File directory = new File(dir);
if(directory.exists())
{
System.out.println("Directory already exists");
}
else
{
System.out.println("Directory not exists, creating now");
success = directory.mkdir();
if(success)
System.out.println("Successfuly created new directory");
else
System.out.println("Failed to create new directory");
}
// Creatning new file in Java, only if not exists
System.out.println("Enter file name to be created");
String filename = reader.nextLine();
File f = new File(filename);
if(f.exists())
{
System.out.println("File already exists");
}
else
{
System.out.println("No such file exists, creating now");
success = f.createNewFile();
if(success)
System.out.printf("Successfully created new file: : %s%n", f);
else
System.out.printf("Failed to create new file: %s%n", f);
}
reader.close();
getFile.getAllFiles(directory);
}
}

Your code is completely working. It actually creates the file. You can see the created file in your java project.
Just add this line of code and it will work as you wish.
filename = dir + "\\" + filename;
File f = new File(filename);

I think the best ways --> to change the below lines:
#1.
if(directory.exists())
to below
if (directory.exists() && directory.isDirectory())
#2.
File f = new File(filename);
if(f.exists())
to below
File f = new File(directory,filename);
if (f.exists() && f.isFile()) {

Related

Java functions delete() and renameTo() not deleting nor renaming

public void newEditSportRecord(){
String filepath = "sport.txt"; //exists in C:\Users\Dell\Documents\NetBeansProjects\Assignment\
String editTerm = JOptionPane.showInputDialog("Enter ID of Sport you wish to modify:");
String tempFile = "temp.txt"; // to be created in C:\Users\Dell\Documents\NetBeansProjects\Assignment\
File oldFile = new File(filepath);
System.out.println(oldFile.getAbsolutePath()); // prints C:\Users\Dell\Documents\NetBeansProjects\Assignment\sport.txt
File newFile = new File(tempFile);
System.out.println(newFile.getAbsolutePath()); // prints C:\Users\Dell\Documents\NetBeansProjects\Assignment\temp.txt
String ID, name = "";
try {
FileWriter fw = new FileWriter(tempFile, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
x = new Scanner(new File(filepath));
while (x.hasNextLine()) {
ID = x.next();
System.out.println(ID);
name = x.next();
System.out.println(name);
if (ID.equals(editTerm)) {
newID = JOptionPane.showInputDialog("Enter new Sport ID:");
newName = JOptionPane.showInputDialog("Enter new Sport Name:");
pw.println(newID);
pw.println(newName);
pw.println();
JOptionPane.showMessageDialog(modifySport, "Record Modified");
} else {
pw.println(ID);
pw.println(name);
pw.println();
}
}
x.close();
pw.flush();
pw.close();
oldFile.delete();
File dump = new File(filepath);
newFile.renameTo(dump);
} catch (Exception ex) {
JOptionPane.showMessageDialog(modifySport, ex);
}
}
I have the following function to try and modify a text file. However, it does NOT delete the original file "sport.txt" nor does it rename "temp.txt" to "sport.txt". It DOES read from the file and create a copy of "sport.txt" with all the relevant modifications as "temp.txt". I had suspected it was a problem with the writers but having closed all of them, the issue still persists. Is this simply down to permission problems as the folder exists in the Documents folder on Local Disk?
Yes, it is a permission problem. Either change the permission of the Documents folder and give access to all the permissions to your user or change your working folder.

createNewFile() Throws FileNotFoundException When Given the Correct FilePath

Here is my code below:
public void playerNaming() throws IOException {
Scanner pickName = new Scanner(System.in);
System.out.println("What do you want your username to be?");
String playerName = pickName.nextLine();
userName = playerName;
File file1 = new File("PlayerFiles\\" + playerName + ".txt");
File file2 = new File(file1.getAbsolutePath());
System.out.println(file2);
file2.createNewFile();
BufferedWriter file3 = new BufferedWriter(new FileWriter(file2));
}
On line file2.createNewFile(); It throws
java.io.FileNotFoundException: (Insert correct FilePath here) The system cannot find the path specified
What is wrong? According to all the articles and other stackoverflow questions I have read, this should work.
Check your file path :
public static void main(String args[])
{
try {
// Get the file
File f = new File("F:\\program1.txt");
// Create new file
// if it does not exist
if (f.createNewFile())
System.out.println("File created");
else
System.out.println("File already exists");
}
catch (Exception e) {
System.err.println(e);
}
Note : The file “F:\program.txt” is a existing file in F: Directory.

Need help creating a file in java

I need a file to be created but one is not being created and I have no clue where it has gone wrong
This is where I have the text for the file name created
public class LetterGradeDisplayer {
public static void main(String[] args) {
LetterGradeConverter conv1 = new LetterGradeConverter("c://temp//grade1.txt", 6);
System.out.println("Contents: ");
System.out.println(conv1);
LetterGradeConverter conv2 = new LetterGradeConverter("c://temp//grade2.txt", 6);
System.out.println("Contents: ");
System.out.println(conv2);
This is where the argument for the file name is taken
public LetterGradeConverter(String fileName, int maxGrade) {
File file = new File(fileName);
int Grade[] = new int [maxGrade];
actualLength = maxGrade;
char LetterGradeList[] = new char [maxGrade];
int count = 0;
Scanner scan;
try {
scan = new Scanner(file);
while(scan.hasNextInt()) {
Grade[count] = scan.nextInt();
count++;
}
scan.close();
}
catch(FileNotFoundException e) {
e.printStackTrace();
}
GradeConverter();
This is the error text I am getting:
java.io.FileNotFoundException: c:\temp\grade1.txt (The system cannot find the file specified)
at java.base/java.io.FileInputStream.open0(Native Method)
at java.base/java.io.FileInputStream.open(Unknown Source)
at java.base/java.io.FileInputStream.<init>(Unknown Source)
at java.base/java.util.Scanner.<init>(Unknown Source)
at LetterGrade.LetterGradeConverter.<init>(LetterGradeConverter.java:21)
at LetterGrade.LetterGradeDisplayer.main(LetterGradeDisplayer.java:7)
Exception in thread "main" java.lang.NullPointerException
at LetterGrade.LetterGradeConverter.GradeConverter(LetterGradeConverter.java:36)
at LetterGrade.LetterGradeConverter.<init>(LetterGradeConverter.java:32)
at LetterGrade.LetterGradeDisplayer.main(LetterGradeDisplayer.java:7)
You mention a file not being created, but I see nothing in your code that SHOULD create a file.
Are you expecting new File() to create the file on the filesystem for you? Because it won't, for that you need File#createNewFile
File file = new File("c://temp//testFile1.txt");
//Create the file
if (file.createNewFile()){
System.out.println("File is created!");
}else{
System.out.println("File already exists.");
}
//Write Content
FileWriter writer = new FileWriter(file);
writer.write("Test data");
writer.close();
"Use File.createNewFile() method to create a file. This method returns a boolean value : true if the file is created successfully; false if the file is already exists or the operation failed for some reason." - https://howtodoinjava.com/core-java/io/how-to-create-a-new-file-in-java/

Can not create file in specific directory in Java (The system cannot find the path specified)

I have code that can create file in D disk in my Computer an can write some information in this file.Here is source
File file = new File("D:\\" + filename);
FileWriter writer = new FileWriter(file, true);
writer.write(builder.toString());
writer.close();
System.out.println("done!");
statusText.setText("Information successfully saved!");
statusText.setForeground(Color.BLACK);
This code working correct but when i try to change file directory like this i have exception
File file = new File("D:\\testFolder\\" + filename);
Here is a exception
IOException: D:\testFolder\2017-08-11.csv (The system cannot find the path specified)
What am i doing wrong or how i can solve my problem?
you can not do that if that folder doesnt exist...
you will just get an java.io.FileNotFoundException
create the folder firts
File dir = new File("C:\\" + "__folder");
dir.mkdir();
or
dir.mkdirs();
depending on how deep the parent/child folders go
Try Creating Directory first:
String filename = "myfile";
File file= null;
// Check if directory exists
File directory = new File("D:\\testFolder\\");
if (directory.exists() && directory.isDirectory()) {
//create your file
file = new File(directory +"\\"+ filename);
} else {
// Create directory
directory = new File("C:\\testFolder\\");
if(directory.mkdir()) {
System.out.println("Directory Created");
file = new File(directory +"\\"+ filename);
} else {
System.out.println("Directory is not created");
}
// Create file
}
FileWriter writer = null;
try {
writer = new FileWriter(file, true);
writer.write(builder.toString());
writer.close();
System.out.println("done!");
statusText.setText("Information successfully saved!");
statusText.setForeground(Color.BLACK);
} catch (IOException e) {
e.printStackTrace();
}

Checking existing file empty or not in java

My code is listing .ncat files and printing them to screen. I want to print if there is no .ncat files in directory, it prints out " there is no .ncat files" How can i do that ?
enter code here
File f = null;
String[] paths;
try{
f = new File("C:/Users/BURAK NURÇİÇEK/workspace/cs 222");
paths = f.list();
for(String path:paths)
{
if(path.toLowerCase().endsWith(".ncat")){
System.out.println(path);
}
}
}catch(Exception e){
e.printStackTrace();
}
File has an exists() method. You can check
(new File(path)).exists()
An extremely simple and clear way is to just set a flag to indicate if a .ncat file has been found. If no .ncat was in the directory, the flag will remain false and the statement will be printed. Try the following:
File f = null;
String[] paths;
boolean fileFound = false;
try{
f = new File("C:/Users/BURAK NURÇİÇEK/workspace/cs 222");
paths = f.list();
for(String path:paths)
{
if(path.toLowerCase().endsWith(".ncat")){
System.out.println(path);
fileFound = true;
}
}
if (!fileFound) System.out.println("There are no .ncat files");
}catch(Exception e){
e.printStackTrace();
}
You can use the buffer reader class:
BufferedReader br = new BufferedReader(new FileReader("pathToFile"));
if (br.readLine() == null) {
System.out.println("File is empty");
}
Checking existing file empty or not in java
To check whether a file is empty:
if(new File(pathname).length() > 0)
To check whether a file exist:
if(new File(pathname).exists())
To check whether a file exist in a folder and all it sub-directories, you can recursively check through the folder.
int numberOfFiles = new File(path).listFiles().length;
if(numberOfFiles == 0) {
System.out.println("Empty Directory");
}

Categories

Resources