what is in java importing packages - java

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.

Related

How to copy files from one folder to another using Java?

How can I copy a file from one folder to another using java? I have tried to use
org.apache.commons.io.FileUtils.copyFileToDirectory(pasteItem, destinationPath);
This works if the destination folder does not contain a file with same name. It throws an IOException if I try to paste the file into the folder. However, is there any way to handle this? May be I want to just paste the file with name renamed automatically to pasteItem(1) or something like that. Please suggest.
In fact, I'm getting a new name for the file if the file with same name already exists. I'm not able to figure how to copy the file and then rename. If I rename first and then copy, I'll lose the original file. If I try to copy the file first, then it is giving an exception saying File with same name already exists!
You can use the Java.io.File class.
It has a method that checks if a fill exists.
Example:
//create files
File original =new File("C:\\test\\testfile.txt");
File destination =new File("D:\\test\\file.txt");
//check if file exists.
for(int x=0;destination.exists()==true;x++){
//if file exists then add 1 to file name and check if exists again.
destination=new File("D\\test\\file"+x+".txt");
}
//copy file.
Files.copy(origional, destination, StandardCopyOption.REPLACE_EXISTING);
There is an overloaded version of this method using a boolean flag which will overwrite the destination file if true.
public static void copyFileToDirectory(File srcFile,
File destDir,
boolean preserveFileDate)
throws IOException
http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html#copyFileToDirectory(java.io.File, java.io.File, boolean)
Please refer this site to copy a file from one folder to another.
http://www.mkyong.com/java/how-to-move-file-to-another-directory-in-java/
I am not sure about rename the file automatically

Java:File name sent as string,file not being found

I am trying to read from another file(text1.txt) and write (the contents of text1.txt) into another(text2.txt).
I send these two names as args[0] and args[1].
I must specify that both file are in my src folder of the project and yet I get the FileNotFoundException,and yes I tried with getAbsolutePath() and yet I get the same exception.
This is my code:
public class Test4 {
public void write(String s,String s2) throws Exception
{
File _filein=new File(s);
File _fileout=new File(s2);
_fileout.createNewFile();
PrintWriter _prw=new PrintWriter(_fileout);
BufferedWriter _buffwrt=new BufferedWriter(_prw);
FileInputStream _readfrom=new FileInputStream(_filein.getAbsolutePath());
BufferedReader _read=new BufferedReader(new InputStreamReader(_readfrom));
String _str=_read.readLine();
while(_str!=null)
{
_buffwrt.write(_str+" ");
_buffwrt.flush();
_str=_read.readLine();
}
}
public static void main(String[] args) throws Exception {
Test4 T4=new Test4();
T4.write(args[0],args[1]);
}
}
Manually reading & writing files is always problematic - you should'nt do that unless you know EXACTLY what type of content you're reading/writing and how it is to be aligned. It is much easier to copy files and let the API do all of that work : http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#copy(java.nio.file.Path,%20java.nio.file.Path,%20java.nio.file.CopyOption...)
Copy a file to a target file. This method copies a file to the target
file with the options parameter specifying how the copy is performed.
By default, the copy fails if the target file already exists or is a
symbolic link, except if the source and target are the same file, in
which case the method completes without copying the file. File
attributes are not required to be copied to the target file. If
symbolic links are supported, and the file is a symbolic link, then
the final target of the link is copied. If the file is a directory
then it creates an empty directory in the target location (entries in
the directory are not copied). This method can be used with the
walkFileTree method to copy a directory and all entries in the
directory, or an entire file-tree where required.

java 'File' Object not making the directory and file

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

Java I/O. delete() method not deleting created file from directory

This code creates a .txt in the folder directory (it works) but when comes the time to delete the whole directory or the .txt file using delete() method, nothing happens.
The delete() method works only when I replace the .txt file with an ordinary folder
import java.io.*;
public class Filemkdir {
public static void main(String[] args) throws Exception {
File f = new File("C:/Temp/Java/secret.txt");
FileWriter fSecret = new FileWriter(f);
f.mkdir();
f.delete();
}
}
On Windows you can't delete an open file. Close the FileWriter first.
Also, the
f.mkdir();
seems completely pointless.
Maybe the fSecret (FileWriter) needs to be closed first. Otherwise the file is "in use"
fSecret.close();
You would basically need to close the writer object before deleting the file
File delete work on file, if you are trying to delete directory you first need to delete all files inside id.
with your code you are giving path for file, but you are creating directory after that.

why new FileWriter("abc.txt") creates a new file and new File("abc.txt") does not?

new File("abc.txt") does not create actual file while new FileWriter("abc.txt") creates a file on disk. While going through source code i found that new FileWriter("abc.txt") eventually creates an object of file like new File()
Constructor of Class java.io.File does not create file on disk. It is just a abstraction over the file path. The file is created when you write to the file.
When you are creating FileWriter it calls constructor of FileOutputStream that calls a sequence of security checks and then invokes:
if (append) {
openAppend(name);
} else {
open(name);
}
Invocation of open() creates file on disk.
EDIT:
Here is how open() is defined:
/**
* Opens a file, with the specified name, for writing.
* #param name name of file to be opened
*/
private native void open(String name) throws FileNotFoundException;
I think file.createNewFile() creates the new file in actual.. please see following code for detal...
File file = new File("D:\\tables\\test.sql");
// if file does not exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
File doesn't always need to represent an actual file, it can be something you plan on creating, are guessing at the existence of, or something you've deleted as well.
From the JavaDoc for java.io.File:
An abstract representation of file and directory pathnames.
and
Instances of this class may or may not denote an actual file-system object such as a file or a directory.
In order to have the file actually be created, one needs to call createNEwFile(), whic according to the JavaDoc:
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 File object is simply a representation of a file's location (URL) in the system. You can call createNewFile() on a File object in order to write our a file assuming one with that name does not already exist in that location.
When FileWriter creates a new File object internally, this is not what causes the file to come into existence. That happens in other parts of the code. A File object is just a standard way to designate a file (or directory), whether or not it exists.
There are lots of reasons really, but:
File is used by many classes in java.io. FileReader, etc... FileWriter is a "convenience" class that uses File and it enables the programmer to be more productive. Some Classes just want a File object which points to a file location and then they operate on it as needed to support their processing. Other Classes might support a FileWriter because it will only be writing to a file and not reading. It also makes the API more strongly-typed.

Categories