i want to save an image (from a url) to my disk by the below code.
i want the code save this image in the location of java code. for example, if the source java code is in D:\example\saveimage.java, this image saves in D:\example\image.jpg. this location may be changed in the install process.
how can i do this? what is its java code?
thank you
public static void main(String[] args) throws Exception {
String imageUrl ="http://imgs.yooz.ir/yooz/walls/yooz-950625.jpg";
String destinationFile = "E:\\Picture\\Wallpaper.jpg";
//destinationFile = location of the source java code
saveImage(imageUrl, destinationFile);
}
public static void saveImage(String imageUrl, String destinationFile) throws IOException {
URL url = new URL(imageUrl);
byte[] b = new byte[2048];
int length;
try {
InputStream is=url.openStream();
OutputStream os = new FileOutputStream(destinationFile);
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}
is.close();
os.close();
}
}catch (UnknownHostException e){
e.printStackTrace();
}
}
String destinationFile = "E:\\Picture\\Wallpaper.jpg";
this is a straight addressing. you can use relative addressing
for example here use:
String destinationFile = "Wallpaper.jpg";
just saves image in Wallpaper.jpg and in the same folder as java file
There are several ways to do this:
save the file in the current directory, or to a path relative to current directory
have the path of the directory in a properties file, the properties file being in the classpath
define a system property
pass the path as an argument
etc...
Related
This spring app performs simple file upload,
here's the controller class
#Override
public String fileUpload(MultipartFile file) {
try{
// save uploaded image to images folder in root dir
Files.write(Paths.get("images/"+ file.getOriginalFilename()), file.getBytes());
// perform some tasks on image
return "";
} catch (IOException ioException) {
return "File upload has failed.";
} finally {
Files.delete(Paths.get("images/" + file.getOriginalFilename()));
}
}
but when i build jar and runs, it throws IOException saying,
java.nio.file.NoSuchFileException: images\8c9.jpeg.
So my question is how can i add the images folder inside the jar executable itself.
Thanks.
You should provide a full path for the images folder, or save in java.io.tmpdir creating the image folder first.
But, in my opinion you should configure your upload folder from a config file for flexibility. Take a look at this.
app:
profile-image:
upload-dir: C:\\projs\\web\\profile_image
file-types: jpg, JPG, png, PNG
width-height: 360, 360
max-size: 5242880
In your service or controller, do whatever you like, may be validate image type, size etc and process it as you like. For instance, if you want thumbnails(or avatar..).
In your controller or service class, get the directory:
#Value("${app.image-upload-dir:../images}")
private String imageUploadDir;
Finally,
public static Path uploadFileToPath(String fullFileName, String uploadDir, byte[] filecontent) throws IOException {
Path fileOut = null;
try{
Path fileAbsolutePath = Paths.get(StringUtils.join(uploadDir, File.separatorChar, fullFileName));
fileOut = Files.write(fileAbsolutePath, filecontent);
}catch (Exception e) {
throw e;
}
return fileOut; //full path of the file
}
For your question in the comment: You can use java.io.File.deleteOnExit() method, which deletes the file or directory defined by the abstract path name when the virtual machine terminates. TAKE A GOOD CARE THOUGH, it might leave some files if not handled properly.
try (ByteArrayOutputStream output = new ByteArrayOutputStream();){
URL fileUrl = new URL(url);
String tempDir = System.getProperty("java.io.tmpdir");
String path = tempDir + new Date().getTime() + ".jpg"; // note file extension
java.io.File file = new java.io.File(path);
file.deleteOnExit();
inputStream = fileUrl.openStream();
ByteStreams.copy(inputStream, output); // ByteStreams - Guava
outputStream = new FileOutputStream(file);
output.writeTo(outputStream);
outputStream.flush();
return file;
} catch (Exception e) {
throw e;
} finally {
try {
if(inputStream != null) {
inputStream.close();
}
if(outputStream != null) {
outputStream.close();
}
} catch(Exception e){
//skip
}
}
there is a text file that an application produces, I would like to take that file and read it as strings in my application. How can I achieve that, any help would be grateful. Both applications are my applications so I can get the permissions.
Thank you!
This is possible using the standard android-storage, where all the user's files are stored too:
All you need to do is to access the same file and the same path in both applications, so e.g.:
String fileName = Environment.getExternalStorageDirectory().getPath() + "myFolderForBothApplications/myFileNameForBothApplications.txt";
Where myFolderForBothApplications and myFileNameForBothApplications can be replaced by your folder/filename, but this needs to be the same name in both applications.
Environment.getExternalStorageDirectory() returns a File-Object to the common, usable file-directory of the device, the same folder the user can see too.
By calling the getPath() method, a String representing the path to this storage is returned, so you can add your folder/filenames afterwards.
So a full code example would be:
String path = Environment.getExternalStorageDirectory().getPath() + "myFolderForBothApplications/";
String pathWithFile = path + "myFileNameForBothApplications.txt";
File dir = new File(path);
if(!dir.exists()) { //If the directory is not created yet
if(!dir.mkdirs()) { //try to create the directories to the given path, the method returns false if the directories could not be created
//Make some error-output here
return;
}
}
File file = new File(pathWithFile);
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
//File couldn't be created
return;
}
Afterwards, you can write in the file or read from the file as provided e.g. in this answer.
Note that the file stored like this is visible for the user and my be edited / deleted by the user.
Also note what the JavaDoc for the getExternalStorageDirectory() says:
Return the primary external storage directory. This directory may not currently be accessible if it has been mounted by the user on their computer, has been removed from the device, or some other problem has happened. You can determine its current state with getExternalStorageState().
I do not know if this is the best/safest way to fix your problem, but it should work.
You can save the text file from your assets folder to anywhere in the sdcard, then you can read the file from the other application.
This method uses the getExternalFilesDir, that returns the absolute path to the directory on the primary shared/external storage device where the application can place persistent files it owns. These files are internal to the applications, and not typically visible to the user as media.
private void copyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
if (files != null) for (String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
File outFile = new File(Environment.getExternalStorageDirectory(), filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// NOOP
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
// NOOP
}
}
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
And to read:
File dir = Environment.getExternalStorageDirectory();
File yourFile = new File(dir, "path/to/the/file/inside/the/sdcard.ext");
I have this project structure:
/webapp
/res
/img
/profile.jpg
/WEB-INF
And I need to save file to res/img/ directory. This time I have this code:
public String fileUpload(UploadedFile uploadedFile) {
InputStream inputStream = null;
OutputStream outputStream = null;
MultipartFile file = uploadedFile.getFile();
String fileName = file.getOriginalFilename();
File newFile = new File("/res/img/" + fileName);
try {
inputStream = file.getInputStream();
if (!newFile.exists()) {
newFile.createNewFile();
}
outputStream = new FileOutputStream(newFile);
int read = 0;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
}
return newFile.getAbsolutePath();
}
But it saving files to user.dir directory, which is ~/Work/Tomcat/bin/.
So how I can upload files to res directory?
You shouldn't really be uploading files there.
If you are using a war, redeploying will delete them. If they are intended to be temporary then use an os assigned temporary location.
If you intend to publish them afterwards then choose a location in which to store the files on your server, make this location known to the application and save and load files from the location.
If you are trying to replace resources dynamically such as an image which is referenced in the html or css templates, then consider publishing the external location separately, you can use mvc:resources for this e.g:
<mvc:resources mapping="/images/**" location="file:/absolute/path/to/image/dir"/>
and you would save your files to that location. This will make it more permanent between deployments.
To save an image to that location using your code you will need to add this into your bean definition (assuming you are using xml configuration without annotations):
<property name="imagesFolder" value="/absolute/path/to/image/dir"/>
and keeping your code as similar as possible change it to:
private String imagesFolder;
public void setImagesFolder(String imagesFolder) {
this.imagesFolder = imagesFolder;
}
public String fileUpload(UploadedFile uploadedFile) {
InputStream inputStream = null;
OutputStream outputStream = null;
MultipartFile file = uploadedFile.getFile();
String fileName = file.getOriginalFilename();
File newFile = new File(imagesFolder + fileName);
try {
inputStream = file.getInputStream();
if (!newFile.exists()) {
newFile.createNewFile();
}
outputStream = new FileOutputStream(newFile);
int read = 0;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
}
return newFile.getAbsolutePath();
}
Please bear in mind that you need to change /absolute/path/to/image/dir to an actual path that exists, also I would recommend to look at the Spring Resources documentation for a better way to deal with files and resources.
Please refer FileUploadController from here to save file to the specified directory.
public String fileUpload(UploadedFile uploadedFile) {
InputStream inputStream = null;
OutputStream outputStream = null;
MultipartFile file = uploadedFile.getFile();
String rootPath = System.getProperty("user.dir");
File dir = new File(rootPath + File.separator + "webapp"+File.separator+"res"+File.separator+"img");
if (!dir.exists())
dir.mkdirs();
String fileName = file.getOriginalFilename();
File serverFile = new File(dir.getAbsolutePath() + File.separator + fileName);
try {
inputStream = file.getInputStream();
if (!newFile.exists()) {
newFile.createNewFile();
}
outputStream = new FileOutputStream(newFile);
int read = 0;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
}
return newFile.getAbsolutePath();
}
I cant understand what the error of this code.
public void run(String url) {
try {
FileInputStream file;
file = new FileInputStream(this.getClass().getResource(url));
Player p = new Player(file);
p.play();
}catch(Exception e){
System.err.print( url + e);
}
}
when i try to run it, it says me "no suitable constructor found for FileInputStream(URL)". Why its happening?
Use:
getClass().getResourceAsStream(classpathRelativeFile) for classpath resources
new FileInputStream(pathtoFile) for file-system resources.
Put the file in root of folder of your class path (folder where your .class files are generated) and then use statements below:
InputStream inputStream =
getClass().getClassLoader().getResourceAsStream(filePath);
Player p = new Player(inputStream );
Here filePath is the relative file path w.r.t. the root folder.
It is simpler to use getResourceAsStream
InputStream in = getClass().getResourceAsStream(url);
Player p = new Player(file);
The parameter of FileInputStream constructor is File, String ... (see http://docs.oracle.com/javase/6/docs/api/java/io/FileInputStream.html ), but Class.getResource return URL (see http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html), not File, or String.
Try to use
public void run(String url) {
try {
FileInputStream file;
file = new FileInputStream(new File(this.getClass().getResource(url).toURI()));
Player p = new Player(file);
p.play();
}catch(Exception e){
System.err.print( url + e);
}
}
I have to do simple file operations code based,including copy/delete operations.The problem is if i declare the file location as a path
File remotefile = new File("//mypc/myfolder/myjar.JAR");
Windows finds the file in the network and does the operations.How ever Linux machines can not find the file.If i were to use:
File remotefile = new File("file://mypc/myfolder/myjar.JAR");
Both platforms find the file.Now i have a method to copy the files which is:
public static void copyFile(File sourceFile, File destFile) throws IOException {
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();
}
}
}
If I were to send the file URI to this method, both platforms can not find the file. But if I send it as a path, windows machines work properly but linux machines can not find the file.
What could be the problem here?