save image directly to specified folder in ascending order of filename - java

Main thing is that I am fresher in JAVA. I got stuck with some code.
I want to save an image capture by a button directly in a specific folder. up to now I am using a file chooser to save my image
I want to save image in C:\temp and file name can be image,image1,image2 in ascending order
int returnVal = jFileChooser1.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
File file = jFileChooser1.getSelectedFile();
Highgui.imwrite(file.getPath(), frame);
} else {
System.out.println("file access cancelled by user.");
}

I don't know JAVA so someone may give you a more specific answer but all you need to do is add a counter onto your file path. The pseudocode algorithm would be this:
Initialise Counter = 0
Get file path - C:/temp
Get file name - Image
Append counter to file name - Image1
Add on image type - Image1.png
Append file path and name - C:/temp/Image1.png
counter++;
Edit:
Here is a simple System.Out example of how to build up a string:
System.out.println("C:\Temp " + FileName + ".png" );

Related

How to display content of text file named with current date using java program

I am working on a web application in which it takes action log for every minute i.e.., any action performed will be appended into a text file with current date as its name and if no action performed then it will append current time stamp in that same file. So for everyday one new file will be created and action performed will be appended in that file for that whole day. What I want now is, all those files are present in D:\ -->(presentdate)<--.txt and when I give a particular date in the same format as that of file name in the "text field" and click on submit in my web application it has to show that file present in D drive as a hyper link(if present in the drive) and when I click on the hyperlink it should simply show the content in that file. I want to know how to search for a file in particular folder/drive without mentioning file name directly but searching for files which are having file names in specific format(Example: 27_06_2014.txt).Any suggestions will be very helpful.
Thank you.
String path = "D:" + File.pathSeparator + fileSearched + ".txt";
File f = new File(path);
if(f.exists()) {
//do your stuff
}
//I dont know why would you like to search them as a list but anyways
File dir = new File("D:");
dir.mkdir();
for(String s : dir.list()){
if(s.equalsIgnoreCase(fileSearched)){
//do your stuff
}
}
Here's the documentation for the java.io.File class

How can I load a file when filename is defined in an external text file?

Given a standard text file that I read in with Scanner, where the first line contains the name of an image to read (which is located in the same folder as the text file), how can I use that file name to load the image to display on screen? As it stands right now, I'm getting a javax.imageio.IIOException saying "Can't read input file!" and I can't figure out why not.
Here's the text file:
MapBig.jpg
2
5
439 203 405 253 431 280 499 257 495 217
5
57 147 164 72 190 127 105 300 70 260
Here's my code to read it: image = ImageIO.read(new File(in.nextLine())); where in is an instance of Scanner.
I've also tried using ./MapBig.jpg in the text file and I get the same problem.
I suppose it should also be noted that I'm reading the text file using ClassLoader.getSystemResourceAsStream("map.data");, as this file is in a source folder in my project... same folder again as the file MapBig.jpg
Here's a stack trace when the error comes up:
javax.imageio.IIOException: Can't read input file!
at javax.imageio.ImageIO.read(Unknown Source)
at graphics.MapPanelSettings.<init>(MapPanelSettings.java:32)
at graphics.GameFrame.initialize(GameFrame.java:71)
at graphics.GameFrame.<init>(GameFrame.java:49)
at game.GameLauncher.main(GameLauncher.java:9)
The problem is indeed in the proper location.
You can construct proper path by getting location that you want to use with the ClassLoader :
URL url = ClassLoader.getSystemResource("map.data");
String fileName = in.nextLine();
String dirPath = new File(url.getPath()).getParent();
File myImage = new File(dirPath, fileName);
This should work. Sorry for incomplete original example.
Edit
Well, you don't actually need to calculate your path using "map.data" location. You directly use :
String fileName = in.nextLine();
URL imageUrl = ClassLoader.getSystemResource(fileName);
File myImage = new File(imageUrl.getPath());
Hope that helps.
try with this..
File file = new File(in.nextLine());
if(file.exists()){
image = ImageIO.read(file);
} else {
System.out.println("given file " + file.getName() + " not found.");
}
Your image has to be loaded from the file system, not from the .jar file itself. If your image is located elsewhere on your system (other directory than your .jar file is at), you should use a different file name than MapBig.jpg. You can change the file name in your map.data file, or you add the default directory as prefix to the loaded file name from your map.data file.
Whenever the files you want to load are loacated in the Jar file itself, you need to load them as resource. Check the example bellow:
URL imgUrl = getClass().getResource(in.nextLine());
ImageIcon imgIcon = new ImageIcon(imgUrl);
Image img = imgIcon.getImage();
If your image is located in a sub-directory, you need to prepend your file name with the proper directory path, for example:
URL imgUrl = getClass().getResource("resources/" + in.nextLine());
ImageIcon imgIcon = new ImageIcon(imgUrl);
Image img = imgIcon.getImage();
You should also debug whether the file name that needs to be loaded is correct. For example, temporarily replace your image = ImageIO.read(new File(in.nextLine())); line with System.out.println("File to load: " + in.nextLine().toString()); and make sure this name is correct. You can easily use the following script to automatically check whether the file (you're trying to load) exists, and print an error if that's not the case;
File f = new File(in.nextLine());
if(f.exists() && f.isFile())
image = ImageIO.read(f);
else
System.out.println("Unable to load image, file doesn't exist: " + f.getName());

Obtaining name of uploaded image with servlet 3.0

Hello i am making a servlet that gets the image from a
Everything in my servlet works fine. The only problem is that i want to know what is the name of the uploaded image so that i can store its full path in a database. How to i so that?
This is the code that upload the file but, it doesn't provide me the actual name of the original image. f.getName gives me the name of my tag.
Part f= request.getPart("imgCoverInserisci");
InputStream imageInputStream = f.getInputStream();
System.out.println("Path where image will be saved: "+request.getContextPath()+"/Immagini/");
/*returns null*/ String nomeFile=request.getParameter("imgCoverInserisci");
f.getName(); //return name of input tag
FileOutputStream out = new FileOutputStream ("C:\\Users\\Salvatore\\Documents\\NetBeansProjects\\TestFumettopoli\\web\\Immagini\\copertineFumetti\\"+nomeFile);
// write bytes taken from uploaded file to target file
int ch = imageInputStream.read();
while (ch != -1) {
out.write(ch);
ch = imageInputStream.read();
}
out.close();
imageInputStream.close();
I solved this problem in a different way. I used javascript to parse the name of the file image everytime the Onchange event occured. The javascript function then assigned the name of the file in a hidden input tag. Later the servlet only needed to read this as a parameter and the trick is done!
the javascript code is here

Delete files using java

In my java application, I'm using FilenameFilter to get zip files in given directory. My directory structure is looks like below.
D\:\MyFiles\data\dir1
D\:\MyFiles\data\dir2
D\:\MyFiles\data\dir3
D\:\MyFiles\data\dir4
zip files are in dir folders. I'm giving only D\\:\\MyFiles\\data to my program and it find folders start with dir using FilenameFilter and then find files ends with zip on dir folders.
Inside a for loop I'm creating new File objects for each zip files and call delete() to delete them, but they aren't deleted.
I have printed file path using getPath() method; output is looks like below.
D\:\MyFiles\data\dir1\a.zip
D\:\MyFiles\data\dir1\b.zip
D\:\MyFiles\data\dir2\b1.zip
D\:\MyFiles\data\dir3\d.zip
Then I manually created a File object as File f = new File("D/:/MyFiles/data/dir1/a.zip") and try to delete. It succeeded.
How can I delete files? How can I give the correct path?
UPDATES
This is the code what I'm using:
// this contains folders start with 'dir' in 'D:\MyFiles\data\'
Vector<String> dirList = utl.identifyDir(conf);
File dir;
for (int i = 0; i < dirList.size(); i++) {
// in my properties file ITEM_FOLDER is written as ITEM_FOLDER=D\:\\MyFiles\\data
// LOG.fine(conf.readConfig(Configuration.ITEM_FOLDER)); returns D:\MyFiles\data
dir = new File(conf.readConfig(Configuration.ITEM_FOLDER)
+ File.separator + dirList.get(i));
// this contains all the files ends with 'zip' in 'dir' folders in 'D:\MyFiles\data\'
Vector<String> zipFiles = utl.identifyZipFiles(dir);
for (int x = 0; x < zipFiles.size(); x++) {
/* delete */
File sourcePath = new File(
conf.readConfig(Configuration.ITEM_FOLDER)
+ File.separator + dirList.get(i)
+ File.separator + zipFiles.get(x));
boolean sp = sourcePath.delete();
LOG.fine("sourcePath : " + sourcePath.getPath() + " : "
+ sp);
// one of LOG prints is D:\MyFiles\data\dir3\d.zip : false
}
}
After reading your update, I think there are 2 possible things going on here.
You've still got something open in your application. You don't happen to use a FileInputStream or anything?
Another process is keeping the .zip busy. Did you open that file? Try closing the explorer window or something like that.
EDIT: A checklist from an other user:
Check that you've got the path correct, e.g. what does file.exists() return?
Check that you've got permission to delete the file as the user running your application
Check that you haven't got an open handle to the file within your code (e.g. have you just read from it and not closed the input stream?)
Check that you don't have the file opened in a desktop app
When you create a new File-object to test, something is different then when you use getPath. Notice how all the slashes in the pathname are \ instead of /.

Java File.renameTo(File) not working

I'm trying to list a directory's contents, and rename certain files.
public void run(String dirName) {
try {
File parDir = new File(dirName);
File[] dirContents = parDir.listFiles();
// Rename if necessary
for(File f : dirContents) {
System.out.println("f is:\n" + f.toString());
String name = f.getName();
String subbedName = name.replaceAll("\uFFFD", "_");
System.out.println("\n" + "name = " + name + ", subbedName = " + subbedName + "\n");
if(!name.equals(subbedName)) {
File newFile = new File(f.getParentFile(), subbedName);
System.out.println("newFile is:\n" + newFile.toString());
if(!f.renameTo(newFile))
System.out.println("Tried to change file name but couldn't.");
}
}
}
catch(Exception exc1) {
System.out.println("Something happened while listing and renaming directory contents: " + exc1.getMessage());
}
}
When I run this, I get "Tried to change file name but couldn't." I don't believe that Java is considering these files to be "open", so I don't think that's the reason. I've even ran chmod 777 myDir where myDir is the value of the dirName string passed into the run method.
What am I missing here? Why won't Java rename these file(s)? These are CentOS machines.
Edit: Added printouts for both f and newFile, which is as follows:
f is:
/root/path/to/mydir/test�.txt
newFile is:
/root/path/to/mydir/test_.txt
You need to create your new File object with the full pathname of those files. So
String name = f.getName(); // gets the name without the directory
should likely be:
String name = f.getAbsolutePath();
(your search/replace may need to change)
The problem is that f.getName() returns the last name component of the path that is represented by f. You then massage this String and turn it back into a File. But the File now represents a path relative to the current directory, not the directory containing the original path.
As a result your code is actually attempting to rename the files from dirName into the application's current directory. That could fail because files already exist in the current directory with those names, or because the dirName and the current directory are in different file systems. (You cannot rename a file from one filesystem to another ... you have to copy it.)
Please note that a File in Java represents a pathname, not a file or a folder. In your code, the f objects are the pathnames for file system objects (either files or folders) in the directory denoted by the String dirname. Each of these f objects will have a directory part.
There is more than one way to fix your code; for example
change name = f.getName() to name = f.toString()
change new File(subbedName) to new File(f.getParentFile(), subbedName)
I have an alternative / additional theory.
The pathname of the file containing the \uFFFD character is coming out as "mojibake"; i.e. the kind of garbled text that you get when you display encoded text using the wrong encoding. And since we are seeing 3 characters of garbled text, I suspect that it is attempting to display the UTF-8 rendering of \uFFFD as Latin-1.
So my theory is that the same think is happening when the File.renameTo method is converting f to the form that it is going to provide to the system call. For some reason that is no clear to me, Java could be using the wrong encoding, and as a result producing a "name" for the original file that doesn't match the name of the file in the file system. That would be sufficient to cause the rename to fail.
Possibly related questions / links:
File name charset problem in java
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4733494 (Note that Sun decided this was not a Java bug, and most of the "me too" comments on the bug report are from people who do not understand the explanation ...)
f.getName(); only returns the name of the folder, not the full path. So subbedName becomes a relative path file. Try something with f.getCanonicalPath() instead.

Categories

Resources