Replace file with specific name java [duplicate] - java

This question already has answers here:
Copy file in Java and replace existing target
(4 answers)
Closed 6 years ago.
I make a java code that copy paste a file from a source to a destination.
My problem now that in every run a new file is pasted in the destination with numerical name. What I want is, to paste that file in the destination with specific name. And on running one more time a new file is created and replaced by the older. In order to get only one file.
I have used the following code:
String b = System.getProperty("user.home");
String src = b + "\\Desktop\\Nouveau dossier\\History";
String des = b + "\\Desktop\\Nouveau dossier2";
File from = new File(src);
File to = new File(des);
System.out.println("tt");
try {
if (file.exists()) {
FileUtils.copyFileToDirectory(file, to);
long size = from.length();
System.out.println("rr" + size);
} else {
System.out.println("No file");
}
}

first the file variable is not defined anywhere so you are calling function exists() on a null object.
Here's the code that might work for you (I replaced references to file variable with from which appears to be your intent):
try {
if (from.exists()) {
FileUtils.copyFileToDirectory(from, to);
long size = from.length();
System.out.println("rr" + size);
} else {
System.out.println("No file");
}
}

Related

how to check if the file path is invalid/does not exist in java

My task is to save a file in the path specified by the end user (must be an absolute path). Am currently facing three different scenarios as in below:
Path name is invalid (cannot be created) - for ex, path name provided by user : sfg rgdf gfggdgfudf
Path name is invalid (but, it can be created) - for ex : C:\Parent\Child\GrandChildren (here C:\Parent exists whereas Child\GrandChildren does not.
Path name is valid (i.e. directory exists) - for ex : C:\Parent\Test
For the first case, I need to save the file in a default location.
For the second, I need to create directories and save the file.
And for the last, I'll save in the specified path.
Below is my code snippet which is saving the file in default location for both first and second scenarios. Am having difficulty to distinguish between first and second. java.io.File.mkdirs works for the second case, but not for the first.
Please ignore my poor code as am new to this programming language. Any inputs would be much appreciated.
//User input must be absolute path
String saveToFolder = "kut igeiguye jh";
String defaultFolder = "C:\\Parent\\Data";
try{
File file = new File(saveToFolder);
if(!file.exists()){
saveToFolder = defaultFolder;
}
file.mkdirs();
}catch(Exception e){
saveToFolder = defaultFolder;
}
//code to save data in path **saveToFolder**
1) For 1st case use regex to determine if path is valid or not
String regularExpression = "([a-zA-Z]:)?(\\[a-zA-Z0-9_-]+)+\\?" ; // this regex for windows. If you are running in linux then regex will be different.
Pattern pattern = Pattern.compile(regularExpression);
boolean isMatched = Pattern.matches(regularExpression,saveToFolder);
2) Check if path is valid or not again using 1st method. If its valid check if folder exists or not.
File f = new File(saveToFolder);
if (f.exists() && f.isDirectory()) {
...
}
3) If path is valid by first method and if it exists second method .
kut igeiguye jh is happily accepted by most file systems out there. If you don't want spaces in your path/filenames, you already need to check the validity by yourself e.g. using a Regular Expression.
Appreciate all those who added their inputs. I made few changes to my code which works. One of my assignments requirement was that my program must take absolute path as input.
With my below code, am able to save data in default location for case 1; New folders are being created and file is being saved in the newly created folder for case 2; And saving the file in specified path for case 3.
String saveToFolder = "kut igeiguye jh";
String defaultFolder = "C:\\Parent\\Data";
try{
File file = new File(saveToFolder);
boolean dirCreated = file.mkdirs();
if(!dirCreated || (file.getParent().equals(null))){
saveToFolder = defaultFolder;
}
}catch(Exception e){
saveToFolder = defaultFolder;
}
System.out.println("save to folder : " +saveToFolder);
you can use isFile() to valid over exists(). I have not checked for all cases but this should help you.
public static void checkPath(){
String saveToFolder = "file/User.txt";
String defaultFolder = "file/data/";
try{
File file = new File(saveToFolder);
if(!file.isFile()){
saveToFolder = defaultFolder;
System.out.println("File not found");
}
file.mkdirs();
}catch(Exception e){
saveToFolder = defaultFolder;
}
}
Java NIO make this simple. The method Files.createDirectories succeeds whether the directory already exists or didn't exist and has been created.
try {
Files.createDirectories(Paths.get(saveToFolder));
}
catch (IOException e) {
System.err.println("Using default folder due to the following exception: " + e);
saveToFolder = defaultFolder;
}
If you really want to check whether the user entered an absolute path, just use Path.isAbsolute().

a file addition by an incomplete (file) name [duplicate]

This question already has answers here:
How to check a file if exists with wildcard in Java?
(7 answers)
Closed 6 years ago.
I have a method:
public void setup () {
File file = new File(74761_control_*.xml)
//some code
}
Where * - variable part. Not known in advance how it will exactly be called a file. The program is required to load an xml file with the same name. Is there an elegant way to do this with a standard Java SE API?
The java.nio package has some convencience methods to iterate over directories using a file name pattern:
Path dir = Paths.get("c:\\temp");
Iterator<Path> iterator = Files.newDirectoryStream(dir,
"74761_control_*.xml").iterator();
Now, iterator "holds" all paths that fit to the glob pattern above.
The rest is iterator/file handling:
if (!iterator.hasNext()) {
// file not found
} else {
Path path = iterator.next();
// process file, e.g. read all data
Files.readAllBytes(path);
// or open a reader
try (BufferedReader reader = Files.newBufferedReader(path)) {
// process reader
}
if (iterator.hasNext()) {
// more than one file found
}
}

Moving files is not working in java [duplicate]

This question already has answers here:
How do I move a file from one location to another in Java?
(11 answers)
Closed 6 years ago.
i'm trying in a loop to move files after they are loaded and processed...when I test moving file part individually it works but when I do it all at once it does not work.
Bellow works fine, but moves directories also but I want only the file to be moved.
public class moveFiles {
public static void main(String[] args) {
String getFilesFrom = "D:\\show\\from";
String destDir = "D:\\show\\to\\";
File srcFile = new File(getFilesFrom);
srcFile.renameTo(new File(destDir, srcFile.getName()));
}
}
The code that I have which is not working the moving part is bellow.
for (File child : file.listFiles()) {
if(extensionFilter.accept(child)) {
fr = new FileReader(child);
cm.copyIn("COPY ct"+addExtraZero+month+" FROM STDIN WITH DELIMITER ',' csv", fr);
} else {
System.out.println("No File is elgible to be loaded");
break;
}
getNumberOfFilesProcessed++;
System.out.println("Loading now " + child.getName());
child.renameTo(new File(moveFilesTo, child.getName()));
}
System.out.println("Number of files Loaded is: " + getNumberOfFilesProcessed);
The above code is:
get files from source directory,
loaded it in database
print files name that it loads
get count of files loaded
which all above works but the last part which is to move files to other directory after loading is not working bellow is the section of files that suppose to move the file the loop.
child.renameTo(new File(moveFilesTo, child.getName()));
scratching my heads for two hours any help will be appreciated.
From description of File.renameTo() (emphasis mine):
The rename operation might not be able to move a file from one
filesystem to another, it might not be atomic, and it might not
succeed if a file with the destination abstract pathname already
exists. The return value should always be checked to make sure that
the rename operation was successful
Add:
if( !child.renameTo(new File(moveFilesTo, child.getName())) )
System.out.println("Could not move file");
Or try using move(Path, Path, CopyOption...) method, as this has more options (using File.toPath()).

Java - How I can check if file is exist? [duplicate]

This question already has answers here:
How do I check if a file exists in Java?
(19 answers)
Closed 7 years ago.
I'm creating a file with writeToFile() function.
Before I call writeToFile() function, I want to check if the file already exist or not.
How can I do this?
code:
private void writeToFile(String data, String fileName) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(this.openFileOutput(fileName, Context.MODE_APPEND));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
You could utilize java.io.File and call the .exists() method to check if the file exists.
Use the following code to check if a file already exists.
if(file.exists() && !file.isDirectory()) {
// continue code
}
Using java.io.File
File f = new File(fileName);
if (f.exists()) {
// do something
}
This is a duplicate.
File file = new File("FileName");
if(file.exists()){
System.out.println("file is already there");
}else{
System.out.println("Not find file ");
}
The methods in the Path class are syntactic, meaning that they operate on the Path instance. But eventually you must access the file system to verify that a particular Path exists

Check if file exists without creating it

If I do this:
File f = new File("c:\\text.txt");
if (f.exists()) {
System.out.println("File exists");
} else {
System.out.println("File not found!");
}
Then the file gets created and always returns "File exists". Is it possible to check if a file exists without creating it?
EDIT:
I forgot to mention that it's in a for loop. So here's the real thing:
for (int i = 0; i < 10; i++) {
File file = new File("c:\\text" + i + ".txt");
System.out.println("New file created: " + file.getPath());
}
When you instantiate a File, you're not creating anything on disk but just building an object on which you can call some methods, like exists().
That's fine and cheap, don't try to avoid this instantiation.
The File instance has only two fields:
private String path;
private transient int prefixLength;
And here is the constructor :
public File(String pathname) {
if (pathname == null) {
throw new NullPointerException();
}
this.path = fs.normalize(pathname);
this.prefixLength = fs.prefixLength(this.path);
}
As you can see, the File instance is just an encapsulation of the path. Creating it in order to call exists() is the correct way to proceed. Don't try to optimize it away.
Starting from Java 7 you can use java.nio.file.Files.exists:
Path p = Paths.get("C:\\Users\\first.last");
boolean exists = Files.exists(p);
boolean notExists = Files.notExists(p);
if (exists) {
System.out.println("File exists!");
} else if (notExists) {
System.out.println("File doesn't exist!");
} else {
System.out.println("File's status is unknown!");
}
In the Oracle tutorial you can find some details about this:
The methods in the Path class are syntactic, meaning that they operate on the Path instance. But eventually you must access the file system to verify that a particular Path exists, or does not exist. You can do so with the exists(Path, LinkOption...) and the notExists(Path, LinkOption...) methods. Note that !Files.exists(path) is not equivalent to Files.notExists(path). When you are testing a file's existence, three results are possible:
The file is verified to exist.
The file is verified to not exist.
The file's status is unknown. This result can occur when the program does not have access to the file.
If both exists and notExists return false, the existence of the file cannot be verified.
Creating a File instance does not create a file on the file system, so the posted code will do what you require.
The Files.exists method has noticeably poor performance in JDK 8, and can slow an application significantly when used to check files that don't actually exist.
This can be applied too for Files.noExists, Files.isDirectory and Files.isRegularFile
According this you can use the following :
Paths.get("file_path").toFile().exists()

Categories