How to check image exist in a particular location? - java

Is there any way to check image exist in a particular location except the following code?This code is taking too much time.
static boolean isImage(String image_path){
InputStream input = null;
try{
URL url = new URL(image_path);
input = url.openStream();
return true;
}catch(Exception ex){
return false;
}
}

If you just want to check if the file exists:
static boolean isImage(String image_path){
try{
File f = new File(image_path);
return f.exists();
}catch(Exception ex){
return false;
}
}

Related

How to Save OpenCV (JavaCV) Trained Faces pictures to database?

Recently I complete a project about face recognition using JavaCV. it save faces to computer directory but i want to save those faces to RDBMs like SQLite, MySQL would be welcome.
Code for save image to computer directory
private String createPictureFilePathName(File dir) {
File file = new File(dir.getPath() + "/image-0.png");
int counter = 1;
while (file.exists()) {
file = new File(dir.getPath() + "/image-" + counter + ".png");
counter++;
}
return file.getPath();
}
private static JFileChooser initPictureDirChooser() {
JFileChooser chooser = new JFileChooser();
chooser.setAcceptAllFileFilterUsed(false);
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setCurrentDirectory(new File(System.getProperty("user.home")).getAbsoluteFile());
return chooser;
}
Any leads to make this possible to save images to database?
Get the input stream of the file and save it into db as a blob using preparedstatement.
Example Code :
public boolean saveFile(File file) throws Exception{
boolean completed = false;
ConnectionManager conn = new ConnectionManager();
try {
PreparedStatement statement = conn.getConnection().prepareStatement("QUERY_TO_INSERT_FILE");
statement.setBlob(1, file.getInputStream());
statement.execute();
conn.commit();
completed = true;
} catch (SQLException e) {
conn.rollbackQuietly();
e.printStackTrace();
throw e;
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally{
conn.close();
}
return completed;
}

File Not Found Exception : Open failed:ENOENT

I am new for android, Im downloading image from URL and set in listView. Its working some mobile and not creating file/directory in some mobile.
Its throw error like:
java.io.FileNotFoundException: /storage/emulated/0/.tam/veg.png: open failed: ENOENT (No such file or directory)
I don't know why its throw error like this some mobile. I want to create directory all type of mobile. Please anyone help me.
Here my code:
public class ImageStorage {
public static String saveToSdCard(Bitmap bitmap, String filename) {
String stored = null;
File sdcard = Environment.getExternalStorageDirectory();
File folder = new File(sdcard.getAbsoluteFile(), ".tam");//the dot makes this directory hidden to the user
folder.mkdir();
File file = new File(folder.getAbsoluteFile(), filename) ;
if (file.exists())
return stored ;
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
stored = "success";
} catch (Exception e) {
e.printStackTrace();
}
return stored;
}
public static File getImage(String imagename) {
File mediaImage = null;
try {
String root = Environment.getExternalStorageDirectory().getAbsolutePath();
File myDir = new File(root);
if (!myDir.exists())
return null;
mediaImage = new File(myDir.getPath() + "/.tam/"+imagename);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mediaImage;
}
public static File checkifImageExists(String imagename) {
File file = ImageStorage.getImage("/" + imagename);
if (file.exists()) {
return file;
} else {
return null;
}
}
public static String getImageName(String value){
String getName[] = value.split("/");
return getName[4];
}
}
Below path not in all mobile:
/storage/emulated/0/
Thanks in advance!!
Maybe u should check if there's external storage in the mobile before u use this path
public String getDir(Context context) {
String checkPath = null;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
|| !Environment.isExternalStorageRemovable()) {
checkPath = Environment.getExternalStorageDirectory().getPath();
} else {
checkPath = context.getCacheDir().getPath();
}
return checkPath;
}

Boolean From Text File Online

I want to read from a text file online, then check for a boolean within the first line of the text file. I'm using this to check for updates for an application.
Here's an idea -
public static boolean needsUpdate()
{
URL url;
boolean needs = false;
try
{
url = new URL("https://github.com/../../blob/master/update.txt");
Scanner s = new Scanner(url.openStream());
boolean getUpdate = s.hasNextBoolean();
if (getUpdate = true)
{
needs = true;
}
else
{
needs = false;
}
}
catch (IOException e)
{
e.printStackTrace();
}
return needs;
}
The text inside the file is update = false or update = true.
Do it like that:
try {
URL url = new URL("https://github.com/../../blob/master/update.txt");
Scanner s = new Scanner(url.openStream());
String text = s.nextLine();
s.close();
text = text.replaceAll("update = ", "");
Boolean getUpdate = Boolean.parseBoolean(text);
//do something with the boolean
} catch(Exception ex) {
ex.printStackTrace();
}

Create Database on SD Card From File

I'm working with Android and I'm trying to use a database I already have. I'd like to put it on the SD card. I have the database file in my project's assets folder. How can I make it on the SD card or external storage of whatever device the app is installed on?
//Step1 : Checked accessiblity on sd card
public boolean doesSDCardAccessible(){
try {
return(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED));
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return false;
}
//Step2 : create directory on SD Card
//APP_DIR : your PackageName
public void createAndInitAppDir(){
try {
if(doesSDCardAccessible()){
AppDir = new File(Environment.getExternalStorageDirectory(),APP_DIR+"/");
if(!AppDir.exists()){
AppDir.mkdirs();
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
//Step 3 : Create Database on sdcard
//APP_DIR : your PackageName
//DATABASE_VERSION : give Database Vesrion
//DATABASE_NAME : your Databsename Name
public void initDB()
{
try {
//Using SQLiteHelper Class Created Database
sqliteHelper = new SQLiteHelper(Application.this,AppDir.getAbsolutePath()+"/"+DATABASE_NAME,
null, DATABASE_VERSION);
//OR use following
//Creating db here. or db will be created at runtime whenever writable db is opened.
db = SQLiteDatabase.openOrCreateDatabase(AppDir.getAbsolutePath()+"/"+DATABASE_NAME, null);*/
db= sqliteHelper.getWritableDatabase();
db.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
In reference to this answer, you can find the directory of the SD card in Android 4.0+ by trying both of the following (only one should work per device):
new File("/mnt/external_sd/");
or
new File("/mnt/extSdCard/");
On Android <4.0, you can use
Environment.getExternalStorageDirectory();
You can create your SQLite database there. Additionally, if you can't find it, you can iterate over all directories in /mnt/ (note: the sdcard will always be accessible via /mnt/).
Go throuh this link
OR try following
InputStream myInput;
try {
AssetManager assetManager = getAssets();
myInput = assetManager.open("mydatabase.db");
File directory = new File("/sdcard/some_folder");
if (!directory.exists()) {
directory.mkdirs();
}
OutputStream myOutput = new FileOutputStream(directory
.getPath() + "/DatabaseSample.backup");
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
The database is like any other flat file. Just copy it to your SD card.
public boolean backup()
{
File sdcard = Environment.getExternalStorageDirectory();
File data = new File("/data/data/com.mydomain.myappname/databases/");
if (sdcard.canWrite())
{
File input = new File(data, DB_NAME);
File output = new File(sdcard, "android/data/com.mydomain.myappname/databases/");
if(!output.exists())
{
if(output.mkdirs())
{
output = new File(sdcard,
"android/data/com.mydomain.myappname/databases/backup.db");
output.createNewFile();
result = true;
}
else
{
output = new File(sdcard,
"android/data/com.mydomain.myappname/databases/backup.db");
result = true;
}
if(input.exists() && result)
{
FileInputStream source;
FileOutputStream destination;
try
{
source = new FileInputStream(input);
try
{
destination = new FileOutputStream(output);
byte[] buffer = new byte[1024];
int length;
while((length = source.read(buffer)) > 0)
{
destination.write(buffer, 0, length);
}
source.close();
destination.flush();
destination.close();
result = true;
}
catch(Exception e)
{
result = false;
destination = null;
}
}
catch(Exception e)
{
result = false;
source = null;
}
}
else
{
result = false;
}
}
else
{
result = false;
}
}
catch(Exception e)
{
result = false;
}
return result;
}

Trying to check if a file exists in internal storage

The following code is how I am trying to identify if a file exists in the internal storage, MODE_PRIVATE.
public boolean isset(String filename){
FileInputStream fos = null;
try {
fos = openFileInput(filename);
//fos = openFileInput(getFilesDir()+"/"+filename);
if (fos != null) {
return true;
}else{
return false;
}
} catch (FileNotFoundException e) {
return false;
}
//File file=new File(mContext.getFilesDir(),filename);
//boolean exists = fos.exists();
}
However, it goes into the exception and doesn't continue with the code. It doesn't do the return. Why?
hope this method helps you.
public boolean fileExist(String fname){
File file = getBaseContext().getFileStreamPath(fname);
return file.exists();
}
For internal storage, this works for me:
public boolean isFilePresent(String fileName) {
String path = getContext().getFilesDir().getAbsolutePath() + "/" + fileName;
File file = new File(path);
return file.exists();
}
Kotlin: This works for me !!
fun check(path: String?): Boolean
{
val file = File(path)
return file.exists()
}

Categories

Resources