How to get a file without the extension in Java? - java

I'm saving images to my resources folder regardless of the extension, and I want to load them the same way. Example: I want to get the image named "foo" whether it is "foo.jpg" or "foo.png".
Right now I'm loading the image for each extension and returning it if it exists OR trying for the next extension if an exception is thrown like so:
StringBuilder relativePath = new StringBuilder().append("src/main/resources/static/images/").append("/")
.append(id).append("/").append(imageName);
File imageFile = null;
byte[] imageBytes = null;
try {
imageFile = new File(new StringBuilder(relativePath).append(".jpg").toString());
imageBytes = Files.readAllBytes(imageFile.toPath());
} catch (IOException e) {
}
if (imageBytes == null) {
imageFile = new File(relativePath.append(".png").toString());
imageBytes = Files.readAllBytes(imageFile.toPath());
}
I feel like it's not the best way to do that, is there a way to load an image by its name and regardless of the extension?

You need to check it the file exists
File foo = new File("foo.jpg");
if (!foo.exists) {
foo = new File("foo.png");
}
But if you really want to load without using the extension, then you could list the files in directory that match a given pattern.
File dir = new File("/path/to/images/dir/");
File [] files = dir.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return name.matches("foo\\.(jpg|png)");
}
});
File foo = files[0];

Related

Download SQLite file programmatically

In my android application i'm using SQLite database.
And I need to have an option in the app to download the database file.
Because sometimes I need to view the data there , so the user will download the file and send it to me and i will browse it using SQLite browsers.
Is the doable? if yes how?
String src = "/data/data/myPackage/databases/Mydb.db";
String dest = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
copyFileOrDirectory(src , dest);
public static void copyFileOrDirectory(String srcDir, String dstDir) {
try {
File src = new File(srcDir);
File dst = new File(dstDir, src.getName());
copyFile(src, dst);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void copyFile(File sourceFile, File destFile) throws IOException {
if (!destFile.getParentFile().exists())
destFile.getParentFile().mkdirs();
if (!destFile.exists()) {
destFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
destination.transferFrom(source, 0, source.size());
} finally {
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}
}
Usually, the SQLite database is available in the /data/data/your.applications.package/databases/database.db path.
So, you could use that path; however, I suggest that you get the Database Path in the following way:
File dbFile = getDatabasePath("dbname");
String dbPath = dbFile.getPath();
Then, you can copy the database from this folder into the folder that you desire.
Copying the database to the Downloads could simulate the "download" of the SQLite database.

How to get the contents of an InputStream?

I use the following method to get all .class files from an eclipse project. but the returned files are in InputStream format which I can not get the content.
public void setFileList(IContainer container) throws CoreException, IOException {
IResource [] members = container.members();
for (IResource member : members) {
if (member instanceof IContainer) {
setFileList((IContainer)member);
} else if (member instanceof IFile && member.isDerived()) {
IFile file = (IFile)member;
InputStream contents = file.getContents();
this.fileList.add(contents);
}
}
}
How can I get the contents of this InputStream in a string format or a txt file?
If you want to write it into a file then you can directly use apache.commons.io helper method:
final File outputFile = new File("test.txt");
FileUtils.copyInputStreamToFile(inputStream, outputFile);

filePath from JFileChooser is null

I am currently working on a Project and would like to save an object to a file with ObjectOutputStream to a location the user chooses with the help of a JFileChooser. But the object is always saved to the root directory of the program into the file named "null" (%ProjectDirectory%/null).
Here's my method saveObjects, which saves a LinkedList of objects to a file:
public void saveObjects(String filePath) {
try {
FileOutputStream os = new FileOutputStream(filePath);
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(oceanObjects);
oos.close();
os.close();
} catch(IOException e) {
System.err.println(e);
}
}
This instruction calls the method saveObject with the filepath as a parameter (filePath is a String; I already tried to use a File)
saveObjects(view.getFilePath());
view is an instance of OceanLifeView and view.getFilePath() is a getter-method of that class that returns the path where the file should be saved (as a String).
getFilePath() looks like this:
public String getFilePath() {
return filePath;
}
And my OceanLifeView like this:
OceanLifeView(String title, int type) {
if(...) {
...
}else if (title.equals("fileChooser")) {
fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(FILES_ONLY);
if (type == 0) {
//Load Button functions
System.out.println("De-Serialisation started fileChooserGUI!");
returnVal = fileChooser.showOpenDialog(fileChooser);
} else {
//Save Button functions
System.out.println("Serialisation started fileChooserGUI!");
returnVal = fileChooser.showSaveDialog(fileChooser);
}
if (returnVal == JFileChooser.APPROVE_OPTION) {
filePath = fileChooser.getSelectedFile();
}
}
}
I would be very thankful to anybody who can share some insight for the problem I encounter or mistake I made implementing this functionality.
This looks as if you are passing files relative path to FileOutputStream constructor.
Probable cause of that is that filePath is calculated as filePath = selectedFile.getPath() instead it should be calculated like this:
File selectedFile = fileChooser.getSelectedFile();
String filePath = selectedFile.getAbsolutePath();

How to copy file from directory to another Directory in Java

I am using JDK 6.
I have 2 folders names are Folder1 and Folder2.
Folder1 have the following files
TherMap.txt
TherMap1.txt
TherMap2.txt
every time Folder2 have only one file with name as TherMap.txt.
What I want,
copy any file from folder1 and pasted in Folder2 with name as TherMap.txt.If already TherMap.txt exists in Folder2, then delete and paste it.
for I wrote the following code.but it's not working
public void FileMoving(String sourceFilePath, String destinationPath, String fileName) throws IOException {
File destinationPathObject = new File(destinationPath);
File sourceFilePathObject = new File(sourceFilePath);
if ((destinationPathObject.isDirectory()) && (sourceFilePathObject.isFile()))
//both source and destination paths are available
{
//creating object for File class
File statusFileNameObject = new File(destinationPath + "/" + fileName);
if (statusFileNameObject.isFile())
//Already file is exists in Destination path
{
//deleted File
statusFileNameObject.delete();
//paste file from source to Destination path with fileName as value of fileName argument
FileUtils.copyFile(sourceFilePathObject, statusFileNameObject);
}
//File is not exists in Destination path.
{
//paste file from source to Destination path with fileName as value of fileName argument
FileUtils.copyFile(sourceFilePathObject, statusFileNameObject);
}
}
}
I call the above function in main()
//ExternalFileExecutionsObject is class object
ExternalFileExecutionsObject.FileMoving(
"C:/Documents and Settings/mahesh/Desktop/InputFiles/TMapInput1.txt",
"C:/Documents and Settings/mahesh/Desktop/Rods",
"TMapInput.txt");
While I am using FileUtils function, it showing error so I click on error, automatically new package was generated with the following code.
package org.apache.commons.io;
import java.io.File;
public class FileUtils {
public static void copyFile(File sourceFilePathObject,
File statusFileNameObject) {
// TODO Auto-generated method stub
}
}
my code not showing any errors,even it's not working.
How can I fix this.
Thanks
Use Apache Commons FileUtils
FileUtils.copyDirectory(source, desc);
Your code isn't working because in order to use the ApacheCommons solution you will have to download the ApacheCommons library found here:
http://commons.apache.org/
and add a reference to it.
Since you are using JRE 6 you can't use all the NIO file utilities, and despite everyone loving Apache Commons as a quick way to answer forum posts, you may not like the idea of having to add that utility on just to get one function. You can also use this code that uses a transferFrom method without using ApacheCommons.
public static void copyFile(File sourceFile, File destFile) throws IOException {
if (!destFile.exists()) {
destFile.createNewFile();
}
FileInputStream fIn = null;
FileOutputStream fOut = null;
FileChannel source = null;
FileChannel destination = null;
try {
fIn = new FileInputStream(sourceFile);
source = fIn.getChannel();
fOut = new FileOutputStream(destFile);
destination = fOut.getChannel();
long transfered = 0;
long bytes = source.size();
while (transfered < bytes) {
transfered += destination.transferFrom(source, 0, source.size());
destination.position(transfered);
}
} finally {
if (source != null) {
source.close();
} else if (fIn != null) {
fIn.close();
}
if (destination != null) {
destination.close();
} else if (fOut != null) {
fOut.close();
}
}
}
When you upgrade to 7, you will be able to do the following
public static void copyFile( File from, File to ) throws IOException {
Files.copy( from.toPath(), to.toPath() );
}
reference:
https://gist.github.com/mrenouf/889747
Standard concise way to copy a file in Java?

Upload file into Folder Using Blazeds and Flex?

In my Flex Application i'm doing image Uploading Using Blazeds ...
private var fileReference:FileReference;
protected function imageUpload(event:MouseEvent):void
{
// create a fileFilter - class declaration
var imageTypes:FileFilter;
// set the file filter type - jpg/png/gif - init method
imageTypes = new FileFilter("Images (*.jpg, *.jpeg, *.gif, *.png)", "*.jpg; *.jpeg; *.gif; *.png");
fileReference = new FileReference();
fileReference.browse([imageTypes]);
fileReference.addEventListener(Event.SELECT, browseImage);
fileReference.addEventListener(Event.COMPLETE, uploadImage);
}
private function browseImage(event:Event):void {
fileReference.load();
}
private function uploadImage(event:Event):void {
profileImage.source = fileReference.data;
var name:String = fileReference.name;
var directory:String = "/EClassV1/flex_src/Images";
var content:ByteArray = new ByteArray();
fileReference.data.readBytes(content, 0, fileReference.data.length);
var fileAsyn:AsyncToken = userService.uploadImage(name,directory,content);
fileAsyn.addResponder(new mx.rpc.Responder(handler_success, handler_failure));
}
And in my Java Code...
#RemotingInclude
public void uploadImage(String name, String directory, byte[] content) {
File file = new File(directory);
if (!file.exists()) {
file.mkdir();
}
name = directory + "/" + name;
File fileToUpload = new File(name);
try {
FileOutputStream fos = new FileOutputStream(fileToUpload);
fos.write(content);
System.out.println("file write successfully");
fos.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
But it giving... error..
java.io.FileNotFoundException: \EClassV1\flex_src\Images\image001.png (The system cannot find the path specified)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:194)
Actually i want to Sore file into folder and store Database..
Help me..
You need to create the file if it does not exist yet. The method createNewFile() will do this for you:
File fileToUpload = new File(name);
fileToUpload.createNewFile();
try {
FileOutputStream oFile = new FileOutputStream(fileToUpload, false);
...

Categories

Resources