I am programming a basic notepad program and I want it to be able to rename files from the command line. If the user writes "rename" to scanner, the program changes the note's file name according to input, like -rename stack. But if user enter two new note names. Program will error like Invalid note name for renaming. It contains ' '. Enter one word.. If a proposed name is used by an existing file, the program will print File already exists.
How can i do this:
-rename stack
Enter new note name?
stack over
Invalid note name for renaming. It contains 'over'. Enter one word
-rename stack
Enter new note name?
over
File already exists
This is what I've written so far:
...
else if (noteNameSplited[0].equals("rename")) {
File file = new File(noteNameSplited[1]+".ncat");
if(!file.exists()) {
System.out.println("File does not exist !");
}
else {
System.out.println("Enter the new note name");
String data=scan.nextLine();
File file2 = new File(data+".ncat");
file.renameTo(file2);
}
}
This may help you:
https://github.com/openstreetmap/osmosis/blob/master/osmosis-core/src/main/java/org/openstreetmap/osmosis/core/util/AtomicFileCreator.java#L50
if (!tmpFile.exists()) {
throw new OsmosisRuntimeException("Can't rename non-existent file " + tmpFile + ".");
}
// Delete the existing file if it exists.
if (file.exists()) {
if (!file.delete()) {
throw new OsmosisRuntimeException("Unable to delete file " + file + ".");
}
}
// Rename the new file to the existing file.
if (!tmpFile.renameTo(file)) {
throw new OsmosisRuntimeException(
"Unable to rename file " + tmpFile + " to " + file + ".");
}
You can try the following:
public boolean renameTo(File dest) {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkWrite(path);
security.checkWrite(dest.path);
}
return fs.rename(this, dest);
}
Related
Hi there I am currently writing a method in Java where I am trying to create new files but I need those files not to be of the same name, but rather of incrementing name values, like so:
/Users/Myself/Desktop/myFile0.xml
/Users/Myself/Desktop/myFile1.xml
/Users/Myself/Desktop/myFile2.xml
/Users/Myself/Desktop/myFile3.xml
So I have tried to do the following in my code, but I do not understand why when I call the file within the for each loop ( to create a new one) the number does not increment?
public void pickFolder() throws Exception {
chooserFolder.setDialogTitle("Specify your save location");
chooserFolder.setDialogType(JFileChooser.SAVE_DIALOG);
int numbers = 0;
chooserFolder.setSelectedFile(new File("myFile" + numbers++ + ".xml"));
chooserFolder.setFileFilter(new FileNameExtensionFilter("xml file", "xml"));
int userSelection = chooserFolder.showSaveDialog(null);
if (userSelection == JFileChooser.APPROVE_OPTION) {
for (File file : files) {
chooserFolder.setSelectedFile(new File(chooserFolder.getSelectedFile().getAbsolutePath()));
fileToSave = chooserFolder.getSelectedFile();
if (fileToSave.createNewFile()) {
System.out.println("File is created!");
fileToSave = chooserFolder.getSelectedFile();
} else {
JOptionPane.showMessageDialog(null, "File already exists.");
}
System.out.println("Save as file: " + fileToSave.getAbsolutePath());
}
Any help would be greatly appreciated, Thank you!
Your numbers variable should be static;
public static int numbers = 0;
public void pickFolder() throws Exception {
chooserFolder.setDialogTitle("Specify your save location");
chooserFolder.setDialogType(JFileChooser.SAVE_DIALOG);
chooserFolder.setSelectedFile(new File("myFile" + numbers++ + ".xml"));
chooserFolder.setFileFilter(new FileNameExtensionFilter("xml file", "xml"));
int userSelection = chooserFolder.showSaveDialog(null);
if (userSelection == JFileChooser.APPROVE_OPTION) {
for (File file : files) {
chooserFolder.setSelectedFile(new File(chooserFolder.getSelectedFile().getAbsolutePath()));
fileToSave = chooserFolder.getSelectedFile();
if (fileToSave.createNewFile()) {
System.out.println("File is created!");
fileToSave = chooserFolder.getSelectedFile();
} else {
JOptionPane.showMessageDialog(null, "File already exists.");
}
System.out.println("Save as file: " + fileToSave.getAbsolutePath());
}
That way whenever you call pickFolder()-either you create a new instance or use the same instance- your numbers variable stays the same for every instance.
That will be because you are appending it to a string "something" + 1 would be string concatenation in java.
Try something like this :
chooserFolder.setSelectedFile(new File("myFile" + (numbers++) + ".xml"));
This will make sure the number is incremented and then replaced with corresponding value.
When doing this, I am trying to make it "dummy proof" for my coworkers, so if they put in a file path instead of a file - the program doesn't stop so that they can just keep going in the application - it'll just ask them again. However currently
FileNotFoundException: C:\Users\usersname\Desktop\userImports\current (Access is denied)
java.io.FileNotFoundException: C:\Users\usersname\Desktop\userImports\current (Access is denied)
How do I work for this? I don't want it to crash like this, I'd rather it just say, "thats not a file - please try again"
How do I better handle file not found exceptions?
File f;
do {
System.out.print("Please give me the " + type + "file: " );
String file = console.nextLine();
f = new File(file);
} while (!f.exists());
Scanner readMe = null;
try {
readMe = new Scanner(f);
} catch (FileNotFoundException e) {
System.err.println("FileNotFoundException: " + e.getMessage());
e.printStackTrace();
}
return readMe;
}
I'm not sure I understood what you exactly want but this is my answer to what I understood :
Just loop while u don't find the file and you can also add a counter like after 5 times u exit the program.
File f;
boolean found = false ;
while (!found) {
do {
System.out.print("Please give me the " + type + "file: " );
String file = console.nextLine();
f = new File(file);
} while (!f.exists());
Scanner readMe = null;
try {
readMe = new Scanner(f);
found = true ;
} catch (FileNotFoundException e) {
found = false ;
System.err.println("FileNotFoundException: " + e.getMessage());
system.out.printl ( "A problem occured while loading the file please try again ");
//e.printStackTrace();
}
}
return readMe;
}
"Access is denied" means that the file does exist but the user who ran the program is not allowed to access - in your case read - it. It could be, i.a., that the user does not have the necessary authority, or that the file is being held by another program.
Try to use canRead() instead of exists()
do {
...
} while (!f.canRead());
I am trying to remove the last line of a CVS file, to do so I need to rename / delete my input file, I tried several things, but I can't get it to work, this is what I got now:
File inputFile = new File((file.getParent() + "/ExportLijst " + dateFormat.format(date) + ".csv"));
inputFile.setWritable(true, true);
File f = (inputFile);
if (!f.exists())
throw new IllegalArgumentException(
"Delete: no such file or directory: " + inputFile);
if (!f.canWrite())
throw new IllegalArgumentException("Delete: write protected: "
+ inputFile);
if (f.isDirectory()) {
String[] files = f.list();
if (files.length > 0)
throw new IllegalArgumentException(
"Delete: directory not empty: " + inputFile);
}
boolean success = f.renameTo(removeFile);
if (!success)
throw new IllegalArgumentException("Delete: deletion failed");
I also tried this, with no result:
public void forceRename(File source, File target) throws IOException
{
if (target.exists())
target.delete();
source.renameTo(target);
}
Most likely you did not close the file, and then the other file operations will not do on Windows.
The code snippets you have put together for us, are in this way not very coherent - of course.
They look fine, though one would need to see the context. A bit much.
So try ensuring a close:
try (PrintWriter csvOut = ...) {
...
} // Automatic close
So I am creating the following code to create a new file. Does anyone know why it's throwing the exception?
Essentially, I thought it was going to check if a file exists after using the constructor and it doesn't, I thought it would create it but neither happened.
Java Code:
import java.util.Scanner;
import java.lang.Integer;
import java.io.*;
import java.lang.*;
import java.io.File;
class CreateNumberFile{
public static void main(String args[]){
//Ask user for filename and highest number
Scanner in = new Scanner(System.in);
System.out.println("Enter the filename");
String fileName = in.next();
System.out.println("Enter the highest number for this file");
int maxNumber = in.nextInt();
System.out.print("A file titled " + fileName+ " will be created containing a");
System.out.println(" string of numbers with numbers ranging from 0 to: " + maxNumber);
// Create a File object
File myFile = new File("home/Users/Joe/Dropbox/Programming/Java/Projects/g2.txt");
// Tests whether the file or directory denoted by this abstract
//pathname exists.
if (myFile.exists()) {
System.out.println(myFile.getAbsolutePath() +
" File already exists");
} else {
try{
//creates a new, empty file named by this pathname
myFile.createNewFile();
System.out.println(myFile.getAbsolutePath() +
" File Created Successfully");
} catch(IOException e){
System.err.println ("Caught IOException "+e.getMessage());
}
}
}//main
}//class
When I run it, I get the following error:
Output:
Caught IOException The system cannot find the path specified
I thought the code would check if the file exists and if it doesn't, I would use the constructor to create the file? any ideas?
Your path looks like an absolute path, but you seem to have forgotten the slash at its beginning.
If your file doesn't exist(), it could happen that it's parent files don't exist() either, so you should create them:
try {
// create all dirs needed to myFile's parent to exist()
myFile.getParent().mkdirs();
//creates a new, empty file named by this pathname
myFile.createNewFile();
System.out.println(myFile.getAbsolutePath() + " File Created Successfully");
} catch(IOException e) {
System.err.println ("Caught IOException "+e.getMessage());
}
Additionally, you are missing the root / in myFile's path, as Alexey Feldgendler said.
I am trying to save contents in file but first I want to search either file does exist or not. But the code I have written, every time it is returning true.
String fileName=FNameTextField.getText();
File file=new File(fileName);
if(file.exists()&& !file.isDirectory()) {
// It returns true if File or directory does exist
System.out.println("the file or directory you are searching does exist : " );
}else{
// It returns true if File or directory not exists
System.out.println("the file or directory you are searching does not exist : " );
}
Thanks.
Your logic seems to be all screwy, or at least I can't make heads or tails of it
if (file.exists()) {
if (file.isDirectory) {
System.out.println("Directory already exists");
} else {
System.out.println("File exists");
}
} else {
System.out.println("Could not find a file or directory matching your request");
}
Try using method...
file.isFile()
The javadoc says
Tests whether the file denoted by this abstract pathname is a normal file. A file is normal if it is not a directory and, in addition, satisfies other system-dependent criteria. Any non-directory file created by a Java application is guaranteed to be a normal file.
Your logic checks if to see only if it is a file. It will NOT return true if a directory with the name exists as you imply in your print statements.
Make use of this examples which is adopt for you :
File f = new File(filePathString);
if(f.exists()) { /* do something */ }
(or)
import java.io.*;
public class FileChecker {
public static void main(String args[]) {
File f = new File("c:\\mkyong.txt");
if(f.exists()){
System.out.println("File existed");
}else{
System.out.println("File not found!");
}
}
}
(or)
import java.io.*;
public class FileOrDirectoryExists{
public static void main(String args[]){
File file=new File("Any file name or
directory whether exists or not");
boolean exists = file.exists();
if (!exists) {
// It returns false if File or directory does not exist
System.out.println("the file or directory
you are searching does not exist : " + exists);
}else{
// It returns true if File or directory exists
System.out.println("the file or
directory you are searching does exist : " + exists);
}
}
}
1. First get all the files in the folder, and store it in an ArrayList.
Eg:
File f = new File("d:\\MyFolder);
File[] fArr = f.listFiles();
ArrayList<File> fList = new ArrayList<File>();
for ( File file : fArr){
if (file.isFile()){
fList.add(file);
}else{
continue;
}
}
2. Now use getName() method to check the file exists or not....
Assume you are looking for a file named "vivek.txt"
Eg:
boolean b = false;
for (File i : fList){
if ((i.getName).equals("vivek.txt")){
b = true;
break;
}
else{
continue;
}
}