Hi i am trying to upload a file using spring data. When i try to upload file, i get an exception.
My code for file upload is
try {
File file = new File(this.TEMPORARY_FILES_DIRECTORY, Calendar.getInstance().getTimeInMillis() + "_" + fileNameUnderscored);
writeByteArrayToFile(file, form.getFile().getBytes());
FileInputStream inputStream = new FileInputStream(file);
GridFSFile gridFSFile = gridFsTemplate.store(inputStream, "test.png");
PropertyImage img = new PropertyImage();
img.setPropertyUid(gridFSFile.getFilename());
imagesRepository.save(img);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
where TEMPORARY_FILES_DIRECTORY = new File("/home/temp/");
the exception i am getting is
java.io.IOException: File '/home/temp/1392807425028_file' could not be created
on debugging FileUtils class
if (parent.mkdirs() == false) {
throw new IOException("File '" + file + "' could not be created");
}
parent.mkdirs() is false.
Can anyone kindly tell me what is wrong with this code.
Are you sure it's /home/temp and not /home/username/temp? You can't create directories outside your home directory. Try something like Systen.getProperty("user.home") + "/temp", if you'd like to store the files inside your home directory. Anyway, why didn't you choose /tmp to be your temporary directory?
Related
I'm using a desktop app java using swing
I'm using JFilechooser to chose the folder to save my excel file
this 1st part is working,the file is well saved. But I need to open it directly after saving it;
I'm using this code the file is found but not open
File xlsx = new File(path + ".xls");
FileInputStream is = null;
try {
is = new FileInputStream(xlsx);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
HSSFWorkbook workbook2 = new HSSFWorkbook(is);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (xlsx.isFile() && xlsx.exists()) {
System.out.println("hurray! We've just opened a workbook");
} else {
System.out.println("Ahh! there was an error. Please make sure that the file path is correct.");
}
I found this Desktop.getDesktop().open(file); but it works just if I put my file in desktop I need to open it anywhere I save it
thanks for helping
FOUND ANOTHER SOLUTION
UPDATE:
File xlsx = new File(path + ".xls");
try {
Runtime.getRuntime().exec("rundll32 SHELL32.DLL,ShellExec_RunDLL \"" + xlsx + "\"");
} catch (Exception exception) {
exception.printStackTrace();
} // path from JFileChooser();
I want to know how can I use java to confirm a file is a picture file.
I have tried the following code:
public static void main(String[] args) {
// get image format in a file
File file = new File("C:/Users/dell、/Desktop/4.xlsx");
// create an image input stream from the specified fileDD
ImageInputStream iis = null;
try {
iis = ImageIO.createImageInputStream(file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// get all currently registered readers that recognize the image format
Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);
if (!iter.hasNext()) {
System.out.println("Not a picture file");
throw new RuntimeException("No readers found! Unable to read the uploaded file");
}
// get the first reader
ImageReader reader = iter.next();
try {
System.out.println("Format: " + reader.getFormatName());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// close stream
if (iis != null){
try {
iis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
iis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
But it doesn't work perfectly! It shows an exception once the file is not a picture file, so I want to find a better way.
There are too many image extensions. Maybe the best way to validate if a file is an image, is using Regular Expressions. Something like this...
([^\s]+(\.(?i)(jpg|png|gif|bmp|MORE|IMAGE|EXTENSIONS))$)
Here is a complete example of the implementation.
Use ImageIO#read.
public static boolean isPictureFile(File file){
try{
return ImageIO.read(file) != null;
}catch(Exception ex){
return false;
}
}
Basically, the method ImageIO.read(File) will return a BufferedImage object when it successfully read the image file, a null otherwise. All we have to do is to let ImageIO read the file and check if it returns a null or not, and if there it throws an exception for whatever reason, we can safely assume the file is not a picture file.
Like in the method i have attached i have used practiceData.txt i am getting same results while using just practiceData in file constructor so is it ok to use file without any extension or txt is better?
private void saveData(String data) {
File file = new File(this.getFilesDir(), "practiceData.txt");
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(data.getBytes());
saveStatus = "Data was successfully saved.";
} catch (java.io.IOException e) {
e.printStackTrace();
saveStatus = "Error occurred: " + e.toString();
} finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
It doesn't matter what file extension you use, it just tells the OS how to open the file. So yes, you can use no extension and it will work just as well.
If you intend the file to be opened manually via another application, it may be helpful to use a standard extension however.
i would like to handle a a properties file in my android app. The Properties-File is in the main-Folder, in the folder with the other jar-files. I know, that´s not best.
Code:
InputStream propStream=MainActivity.class.getResourceAsStream("data.properties");
Log.d("propStreamOutput",propStream.toString());
File data = new File(propStream.toString());
Reader reader;
try {
reader = new FileReader(data);
dataProp = new Properties();
dataProp.load( reader );
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
so, the log at line 2 says:
libcore.net.url.JarURLConnectionImpl$JarURLConnectionInputStream#421302e8
in this form logcat calls a System.err :
java.io.FileNotFoundException/libcore.net.url.JarURLConnectionImpl$JarURLConnectionInputStream#42097218: open failed: ENOENT (No such file or directory)
but when I comment like this:
InputStream propStream=MainActivity.class.getResourceAsStream("data.properties");
Log.d("propStreamOutput",propStream.toString());
File data = new File(propStream.toString());
// Reader reader;
// try {
// reader = new FileReader(data);
// dataProp = new Properties();
// dataProp.load( reader );
// } catch (FileNotFoundException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
// catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
then there is no system.err ! Of course the log call at line 2 says the same.
If you really wanna use the getResourceAsStream() then you have to put the file on the "src" folder, together with your .java files.
This is usually the way for standard Java applications, but on Android the most usual way to perform such things is to put the file in the 'assets' folder, via AssetsManager, which is accessible from your Activity or any Context. like shown below:
InputStream is = null;
try {
is = context.getAssets().open("data.properties");
} catch (final IOException e) {
e.printStackTrace();
} finally {
closeStreamGracefully(is);
}
getRessourceAsStream return an InputStream. When you call toString on this it will return a string representation of the object. Then when you create your data file and try to read it will try to open a file like #sdqzeffdfsf. If you whant to read the properties from this file use Properties
Properties properties = new Properties();
properties.load(propStream);
This is for standard java. However in android you usualy use AssetManager
I download audio files from server using
try {
// URL url = new URL("http://commonsware.com/misc/test2.3gp");
URL url = new URL("http://192.168.0.2/supplications/"+fileName);
//URL url = new URL("http://www.msoftech.com/supplications/android/"+fileName);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
Log.v("log_tag", "PATH: " + PATH);
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, fileName);
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1)
{
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
} catch (IOException e) {
Log.d("log_tag", "Error: " + e);
}
Log.v("log_tag", "Check: " +cd2);
Here PATH = "/data/data/packagename/sounds/filename
It works fine, audio file downloaded and played successfully, but my problem is when I click the home button and then restart the app means the folder with the downloaded audio was not found, ie, when exit the app means all the downloaded audios were deleted automatically. It throws the exception file not found.
For playing the downloaded file I used the code as below,
public void audioPlayer(String path, String fileName) throw FileNotFoundException
{
//set up MediaPlayer
FileInputStream fileInputStream = new FileInputStream(PATH+"/"+fileName);
//String command = "chmod 666 " + recordFile.toString();
try {
mp.setDataSource(fileInputStream.getFD());
// mp.setDataSource(path+"/"+filename.mp3);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
whats the problem with it what I have to do for saving the audio file permenantly.
There is nothing problem in your code it is a file permission issue.
When you download file into internal file system under application package a security is assigned to it like "-rw------" this means your file is accessible for the same application only.As android is on Linux based so every file have some permission.
Your file would be there but not accessible to other application like media player etc, so these application throws error like file not found.(you can check though DDMS tool).
Just change the file path to external drive.
Accept the answer if it is helpful.