I get the name of database file from a user, and I want to check if that file already exists. If it does exist, I want to show an error message to user, but I don't know how to check if the file exists.
public static void databaseConnect(String dbName) throws Exception
{
if (/*same name exists*/) // How do I check this?
{
System.out.print("This database name already exists");
}
else
{
Class.forName("SQLite.JDBCDriver").newInstance();
conn = DriverManager.getConnection("jdbc:sqlite:/"+ dbName);
stat = conn.createStatement();
}
}
public static void databaseConnect(String dbName) throws Exception {
File file = new File (dbName);
if(file.exists()) //here's how to check
{
System.out.print("This database name already exists");
}
else{
Class.forName("SQLite.JDBCDriver").newInstance();
conn = DriverManager.getConnection("jdbc:sqlite:/"+ dbName);
stat = conn.createStatement();
}
Assuming that your dbName parameter indicates the path to the SQLite file ("-wal" and "-shm" companion files notwithstanding), you can use the Java java.io.File class and its exists() predicate:
final File f = new File(dbName);
if (f.exists())
{
if (f.isDirectory())
{
// Warn about the designated name being a directory.
}
else
{
// Warn about the designated name already existing as a file.
}
}
Other checks could be warranted too, such as whether the process has the privilege to create the file, though ultimately SQLite will do a better job ensuring that all its requirements can be fulfilled.
I've found that the best way to do this is to instead check the size of the file. If you execute:
return new File(DB_NAME).exists() should equal True.
You should get a true back because it will create it. Instead check to make sure the file size is greater than 0. At least in this case you know there's data in the file without attaching and querying for results.
Instead do:
return new File(DB_NAME).length() > 0
You can do something like this, I'm guessing you think you are creating a new file in your directory when you do "new File(name)", for what I've red, but that is not what is happening.
public static void databaseConnect(String dbName) throws Exception {
// new File(filename) does not create a new
// file in your file system
File file = new File (dbName);
if (file.exists())
{ // the file already existed and the program will enter this block
System.out.print("Do something");
}
else
{ //the file did not exist and you can send your error msg
System.out.print("Do something else");
}
}
I misinterpreted your question a few times, my bad, but I think that's it.
Something like this?
public boolean databaseExist()
{
File dbFile = new File(DB_PATH + DB_NAME);
return dbFile.exists();
}
late, may it help :
public boolean didPackageCreate() {
File dbfile = this.getDatabasePath("app.db");
if(dbfile.exists()){
// db exist
}else{
// db doesn't exist
}
}
Related
How do I create Directory/folder?
Once I have tested System.getProperty("user.home");
I have to create a directory (directory name "new folder" ) if and only if new folder does not exist.
new File("/path/directory").mkdirs();
Here "directory" is the name of the directory you want to create/exist.
After ~7 year, I will update it to better approach which is suggested by Bozho.
File theDir = new File("/path/directory");
if (!theDir.exists()){
theDir.mkdirs();
}
With Java 7, you can use Files.createDirectories().
For instance:
Files.createDirectories(Paths.get("/path/to/directory"));
You can try FileUtils#forceMkdir
FileUtils.forceMkdir("/path/directory");
This library have a lot of useful functions.
mkdir vs mkdirs
If you want to create a single directory use mkdir
new File("/path/directory").mkdir();
If you want to create a hierarchy of folder structure use mkdirs
new File("/path/directory").mkdirs();
Create a single directory.
new File("C:\\Directory1").mkdir();
Create a directory named “Directory2 and all its sub-directories “Sub2″ and “Sub-Sub2″ together.
new File("C:\\Directory2\\Sub2\\Sub-Sub2").mkdirs()
Source: this perfect tutorial , you find also an example of use.
For java 7 and up:
Path path = Paths.get("/your/path/string");
Files.createDirectories(path);
It seems unnecessary to check for existence of the dir or file before creating, from createDirectories javadocs:
Creates a directory by creating all nonexistent parent directories first. Unlike the createDirectory method, an exception is not thrown if the directory could not be created because it already exists.
The attrs parameter is optional file-attributes to set atomically when creating the nonexistent directories. Each file attribute is identified by its name. If more than one attribute of the same name is included in the array then all but the last occurrence is ignored.
If this method fails, then it may do so after creating some, but not all, of the parent directories.
The following method should do what you want, just make sure you are checking the return value of mkdir() / mkdirs()
private void createUserDir(final String dirName) throws IOException {
final File homeDir = new File(System.getProperty("user.home"));
final File dir = new File(homeDir, dirName);
if (!dir.exists() && !dir.mkdirs()) {
throw new IOException("Unable to create " + dir.getAbsolutePath();
}
}
Neat and clean:
import java.io.File;
public class RevCreateDirectory {
public void revCreateDirectory() {
//To create single directory/folder
File file = new File("D:\\Directory1");
if (!file.exists()) {
if (file.mkdir()) {
System.out.println("Directory is created!");
} else {
System.out.println("Failed to create directory!");
}
}
//To create multiple directories/folders
File files = new File("D:\\Directory2\\Sub2\\Sub-Sub2");
if (!files.exists()) {
if (files.mkdirs()) {
System.out.println("Multiple directories are created!");
} else {
System.out.println("Failed to create multiple directories!");
}
}
}
}
Though this question has been answered. I would like to put something extra, i.e.
if there is a file exist with the directory name that you are trying to create than it should prompt an error. For future visitors.
public static void makeDir()
{
File directory = new File(" dirname ");
if (directory.exists() && directory.isFile())
{
System.out.println("The dir with name could not be" +
" created as it is a normal file");
}
else
{
try
{
if (!directory.exists())
{
directory.mkdir();
}
String username = System.getProperty("user.name");
String filename = " path/" + username + ".txt"; //extension if you need one
}
catch (IOException e)
{
System.out.println("prompt for error");
}
}
}
Just wanted to point out to everyone calling File.mkdir() or File.mkdirs() to be careful the File object is a directory and not a file. For example if you call mkdirs() for the path /dir1/dir2/file.txt, it will create a folder with the name file.txt which is probably not what you wanted. If you are creating a new file and also want to automatically create parent folders you can do something like this:
File file = new File(filePath);
if (file.getParentFile() != null) {
file.getParentFile().mkdirs();
}
This the way work for me do one single directory or more or them:
need to import java.io.File;
/*enter the code below to add a diectory dir1 or check if exist dir1, if does not, so create it and same with dir2 and dir3 */
File filed = new File("C:\\dir1");
if(!filed.exists()){ if(filed.mkdir()){ System.out.println("directory is created"); }} else{ System.out.println("directory exist"); }
File filel = new File("C:\\dir1\\dir2");
if(!filel.exists()){ if(filel.mkdir()){ System.out.println("directory is created"); }} else{ System.out.println("directory exist"); }
File filet = new File("C:\\dir1\\dir2\\dir3");
if(!filet.exists()){ if(filet.mkdir()){ System.out.println("directory is created"); }} else{ System.out.println("directory exist"); }
if you want to be sure its created then this:
final String path = "target/logs/";
final File logsDir = new File(path);
final boolean logsDirCreated = logsDir.mkdir();
if (!logsDirCreated) {
final boolean logsDirExists = logsDir.exists();
assertThat(logsDirExists).isTrue();
}
beacuse mkDir() returns a boolean, and findbugs will cry for it if you dont use the variable. Also its not nice...
mkDir() returns only true if mkDir() creates it.
If the dir exists, it returns false, so to verify the dir you created, only call exists() if mkDir() return false.
assertThat() will checks the result and fails if exists() returns false. ofc you can use other things to handle the uncreated directory.
This function allows you to create a directory on the user home directory.
private static void createDirectory(final String directoryName) {
final File homeDirectory = new File(System.getProperty("user.home"));
final File newDirectory = new File(homeDirectory, directoryName);
if(!newDirectory.exists()) {
boolean result = newDirectory.mkdir();
if(result) {
System.out.println("The directory is created !");
}
} else {
System.out.println("The directory already exist");
}
}
Here is one attractiveness of the java, using Short Circuit OR '||', testing of the directory's existence along with making the directory for you
public File checkAndMakeTheDirectory() {
File theDirectory = new File("/path/directory");
if (theDirectory.exists() || theDirectory.mkdirs())
System.out.println("The folder has been created or has been already there");
return theDirectory;
}
if the first part of the if is true it does not run the second part and if the first part is false it runs the second part as well
public class Test1 {
public static void main(String[] args)
{
String path = System.getProperty("user.home");
File dir=new File(path+"/new folder");
if(dir.exists()){
System.out.println("A folder with name 'new folder' is already exist in the path "+path);
}else{
dir.mkdir();
}
}
}
How do I create Directory/folder?
Once I have tested System.getProperty("user.home");
I have to create a directory (directory name "new folder" ) if and only if new folder does not exist.
new File("/path/directory").mkdirs();
Here "directory" is the name of the directory you want to create/exist.
After ~7 year, I will update it to better approach which is suggested by Bozho.
File theDir = new File("/path/directory");
if (!theDir.exists()){
theDir.mkdirs();
}
With Java 7, you can use Files.createDirectories().
For instance:
Files.createDirectories(Paths.get("/path/to/directory"));
You can try FileUtils#forceMkdir
FileUtils.forceMkdir("/path/directory");
This library have a lot of useful functions.
mkdir vs mkdirs
If you want to create a single directory use mkdir
new File("/path/directory").mkdir();
If you want to create a hierarchy of folder structure use mkdirs
new File("/path/directory").mkdirs();
Create a single directory.
new File("C:\\Directory1").mkdir();
Create a directory named “Directory2 and all its sub-directories “Sub2″ and “Sub-Sub2″ together.
new File("C:\\Directory2\\Sub2\\Sub-Sub2").mkdirs()
Source: this perfect tutorial , you find also an example of use.
For java 7 and up:
Path path = Paths.get("/your/path/string");
Files.createDirectories(path);
It seems unnecessary to check for existence of the dir or file before creating, from createDirectories javadocs:
Creates a directory by creating all nonexistent parent directories first. Unlike the createDirectory method, an exception is not thrown if the directory could not be created because it already exists.
The attrs parameter is optional file-attributes to set atomically when creating the nonexistent directories. Each file attribute is identified by its name. If more than one attribute of the same name is included in the array then all but the last occurrence is ignored.
If this method fails, then it may do so after creating some, but not all, of the parent directories.
The following method should do what you want, just make sure you are checking the return value of mkdir() / mkdirs()
private void createUserDir(final String dirName) throws IOException {
final File homeDir = new File(System.getProperty("user.home"));
final File dir = new File(homeDir, dirName);
if (!dir.exists() && !dir.mkdirs()) {
throw new IOException("Unable to create " + dir.getAbsolutePath();
}
}
Neat and clean:
import java.io.File;
public class RevCreateDirectory {
public void revCreateDirectory() {
//To create single directory/folder
File file = new File("D:\\Directory1");
if (!file.exists()) {
if (file.mkdir()) {
System.out.println("Directory is created!");
} else {
System.out.println("Failed to create directory!");
}
}
//To create multiple directories/folders
File files = new File("D:\\Directory2\\Sub2\\Sub-Sub2");
if (!files.exists()) {
if (files.mkdirs()) {
System.out.println("Multiple directories are created!");
} else {
System.out.println("Failed to create multiple directories!");
}
}
}
}
Though this question has been answered. I would like to put something extra, i.e.
if there is a file exist with the directory name that you are trying to create than it should prompt an error. For future visitors.
public static void makeDir()
{
File directory = new File(" dirname ");
if (directory.exists() && directory.isFile())
{
System.out.println("The dir with name could not be" +
" created as it is a normal file");
}
else
{
try
{
if (!directory.exists())
{
directory.mkdir();
}
String username = System.getProperty("user.name");
String filename = " path/" + username + ".txt"; //extension if you need one
}
catch (IOException e)
{
System.out.println("prompt for error");
}
}
}
Just wanted to point out to everyone calling File.mkdir() or File.mkdirs() to be careful the File object is a directory and not a file. For example if you call mkdirs() for the path /dir1/dir2/file.txt, it will create a folder with the name file.txt which is probably not what you wanted. If you are creating a new file and also want to automatically create parent folders you can do something like this:
File file = new File(filePath);
if (file.getParentFile() != null) {
file.getParentFile().mkdirs();
}
This the way work for me do one single directory or more or them:
need to import java.io.File;
/*enter the code below to add a diectory dir1 or check if exist dir1, if does not, so create it and same with dir2 and dir3 */
File filed = new File("C:\\dir1");
if(!filed.exists()){ if(filed.mkdir()){ System.out.println("directory is created"); }} else{ System.out.println("directory exist"); }
File filel = new File("C:\\dir1\\dir2");
if(!filel.exists()){ if(filel.mkdir()){ System.out.println("directory is created"); }} else{ System.out.println("directory exist"); }
File filet = new File("C:\\dir1\\dir2\\dir3");
if(!filet.exists()){ if(filet.mkdir()){ System.out.println("directory is created"); }} else{ System.out.println("directory exist"); }
if you want to be sure its created then this:
final String path = "target/logs/";
final File logsDir = new File(path);
final boolean logsDirCreated = logsDir.mkdir();
if (!logsDirCreated) {
final boolean logsDirExists = logsDir.exists();
assertThat(logsDirExists).isTrue();
}
beacuse mkDir() returns a boolean, and findbugs will cry for it if you dont use the variable. Also its not nice...
mkDir() returns only true if mkDir() creates it.
If the dir exists, it returns false, so to verify the dir you created, only call exists() if mkDir() return false.
assertThat() will checks the result and fails if exists() returns false. ofc you can use other things to handle the uncreated directory.
This function allows you to create a directory on the user home directory.
private static void createDirectory(final String directoryName) {
final File homeDirectory = new File(System.getProperty("user.home"));
final File newDirectory = new File(homeDirectory, directoryName);
if(!newDirectory.exists()) {
boolean result = newDirectory.mkdir();
if(result) {
System.out.println("The directory is created !");
}
} else {
System.out.println("The directory already exist");
}
}
Here is one attractiveness of the java, using Short Circuit OR '||', testing of the directory's existence along with making the directory for you
public File checkAndMakeTheDirectory() {
File theDirectory = new File("/path/directory");
if (theDirectory.exists() || theDirectory.mkdirs())
System.out.println("The folder has been created or has been already there");
return theDirectory;
}
if the first part of the if is true it does not run the second part and if the first part is false it runs the second part as well
public class Test1 {
public static void main(String[] args)
{
String path = System.getProperty("user.home");
File dir=new File(path+"/new folder");
if(dir.exists()){
System.out.println("A folder with name 'new folder' is already exist in the path "+path);
}else{
dir.mkdir();
}
}
}
I am trying to create a folder call "YouDown" at the moment I don't care where the folder is located but at this time all I want to figure out is creating it. I found that my first issue was that mkdir() and mkdirs() were being ignored due to not knowing it was a Boolean value. I created the Boolean of success and now its not being ignored. Following this I created log.d of each step in detecting to creating to already existing. It registers that it "Doesn't exist" , "Being Created" then either "Created" or "Creation Failed". It jumps to the "Creation Failed". Everything I find now to help is just being repetitive to what I've been reading for the past few days. I am also looking into how I could apply this to a specific path way like the variable string I want it to be created inside the directories Music folder
// Lastest try
String Tag2 = "YouDown"
if (!dir.exists()) {
Log.d(Tag2,"Doesnt Exist");
boolean success = false;
try{
success = dir.mkdir();
Log.d(Tag2,"Being Created");
}
catch(SecurityException se){
//handle it
}
if(success) {
Log.d(Tag2, "Created");
} else{
Log.d(Tag2, "Creation Failed");
}
}
// Other Try
String path = "/sdcard/Music/Youdown"
if(new File(path).exists()){
Log.d(Tag2, "Exists");
} else {
Log.d(Tag2, "Being Created");
Boolean succes = new File(path).mkdir();
if(success){
Log.d(Tag2, "Created"
} else {
Log.d(Tag2, "Failed"
}
Newest attempt
File dir = new File(Environment.getExternalStorageDirectory(), path2);
Boolean A = dir.mkdirs();
if(A){
Log.d(Tag2,"Created");
}
if(!A){
Log.d(Tag2,"Failed");
}
Although Android has a hierarchical file system your app may read and write in certain places only. As a start I suggest using the method getDir() of android.content.Context. As the doc states:
Retrieve, creating if needed, a new directory in which the application can place its own custom data files. You can use the returned File object to create and access files in this directory. Note that files created through a File object will only be accessible by your own application; you can only set the mode of the entire directory, not of individual files.
If you want to access shared directories you need to call other methods, for example Context.getExternalFilesDir().
If you are creating the directory for your app only, such that if ever your app gets deleted the folder gets deleted too, you can use getFilesDir().
File internalDir = getContext().getFilesDir();
String path = "/Music/Youdown";
// to create it you can call, new File(internalDir, path).mkdir();
Or alternatively if you want the external storage you would use the Environment.getExternalStorage(); like below:
String path = "/Music/Youdown";
File f = new File(Environment.getExternalStorageDirectory(), path );
if (!f.exists()) {
f.mkdirs();
}
I am trying to access a file in remote shared location.
////hostname//data//upload//123//test.txt
File sourceFile=new File("////hostname//data//upload//123//test.txt");
sysout("sourceFile.exists()"+sourceFile.exists())//returning false
If a directory is empty file.exists() is returning true.
I am using Java 1.6
I don't understand what is this weird behavior.
First of all to come back to Erwin´s suggestion, this is not the right attempt. The character \ is used in Java as an escape sequence, usually to print out reserved characters. For example will
String s = "The weather is really "nice" today";
result in an error, as " is already reserved for strings. The correct version would be
String s = "The weather is really \"nice\" today";
Coming back to the question, you have to know that when you create a file and test if it exists Java will validate the abstract pathname of the file. That said, if your abstact path is a directory and it exists true will be returned.
Edit:
If you intend to check if an abstract pathname is a directory try the following:
// Check if a file is a directory
if(file.isDirectory()) {
}
// Check if a file contains something
if(file.list().length > 0) {
}
Check this example ,it checks the directory else creates a new one then your new file created.
File f = new File("D:/image_send");
File file = new File("D:/image_send/" + date + ".txt");
try {
if(!f.isDirectory()){
f.mkdirs();
}
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("File created Success");
public static boolean fileTransfer(String src, String des) throws Exception {
if (des == null || des.equals("") || src == null || src.equals("")) {
return false;
}
File fileExisting = new File(src);
File fileNew = new File(des+ fileExisting.getName());
if (fileExisting.exists() && !fileExisting.isDirectory()) {
if (fileExisting.renameTo(fileNew)) {
System.out.println("File is moved successful!");
} else {
System.out.println("File is failed to move!");
}
}
return fileNew.exists();
}
This is the code for file transfer as per your comment ,use src as sourcepath and des as destination path if you get a boolean false,that means path given is wrong.
I am looking for a away to rename a file to a string. renameTo only takes another file as a parameter, but I want it to take a string. So basically, how do I implement this method here?
public static void renameFile(File toBeRenamed, String new_name) {
}
I would like to rename the file "toBeRenamed" to "new_name". Do I have to make another file called new_name, or is there some workaround? Thanks!
EDIT: Thanks for the answer Luiggi. Here is a pic of the new error:
The File class doesn't represent the physic file in the hard drive, it is just an abstract representation. Creating a new instance of File class doesn't mean you are creating a physical file.
By knowing this, you can rename your file using a new File without worrying about creating new physical files. Code adapted from Rename a file using Java:
public static void renameFile(File toBeRenamed, String new_name)
throws IOException {
//need to be in the same path
File fileWithNewName = new File(toBeRenamed.getParent(), new_name);
if (fileWithNewName.exists()) {
throw new IOException("file exists");
}
// Rename file (or directory)
boolean success = toBeRenamed.renameTo(fileWithNewName);
if (!success) {
// File was not successfully renamed
}
}
EDIT: Based on your question update and on this comment:
I took a pic of the error. "Unhandled Exception Type IO Exception"
Looks one of these:
You don't know how to handle checked exceptions.
To do this, you should wrap the method that throws the Exception (or subclass) in a try-catch statement:
String new_name = getFilename(file);
try {
renameFiles(files[i], new_name);
} catch (IOException e) {
//handle the exception
//using a basic approach
e.printStacktrace();
}
More info: Java Tutorial. Lesson: Exceptions.
You don't want your method to throw a checked exception. In this case, it would be better to throw an unchecked exception instead, so you don't need to handle the exception manually. This can be done by throwing a new instance of RuntimeException or a subclass of this:
public static void renameFile(File toBeRenamed, String new_name) {
File fileWithNewName = new File(new_name);
if (fileWithNewName.exists()) {
throw new RuntimeException("file exists.");
}
// Rename file (or directory)
boolean success = toBeRenamed.renameTo(fileWithNewName);
if (!success) {
// File was not successfully renamed
}
}
More info in the link posted in the above section.
You don't want to throw an exception at all. In this case, it would be better to at least return a value to know if the file was exactly renamed:
public static boolean renameFile(File toBeRenamed, String new_name) {
//need to be in the same path
File fileWithNewName = new File(toBeRenamed.getParent(), new_name);
if (fileWithNewName.exists()) {
return false;
}
// Rename file (or directory)
return toBeRenamed.renameTo(fileWithNewName);
}
And update your code accordingly:
String new_name = getFilename(file);
boolean result = renameFiles(files[i], new_name);
if (!result) {
//the file couldn't be renamed
//notify user about this
System.out.println("File " + files[i].getName() + " couldn't be updated.");
}
Which one to choose? Will depend entirely on your taste. If I were you, I would use the third option for a quick dirty or learning phase work, but for a real world application I would use second option but using my own custom exception that extends from RuntimeException.
Perhaps this could be useful for you
// File (or directory) with old name
File file = new File("oldname");
// File (or directory) with new name
File file2 = new File("newname");
if(file2.exists()) throw new java.io.IOException("file exists");
// Rename file (or directory)
boolean success = file.renameTo(file2);
if (!success) {
// File was not successfully renamed
}
This is extracted from a similar question Rename a file using Java