I have a Java method that takes byte array and String value as arguments and returns a File object. This is the code
public File createTempFile(byte[] byteArray, String fileName) throws IOException {
String prefix = FilenameUtils.getBaseName(fileName);
String suffix = getMimeType(byteArray);
File tempFile = File.createTempFile(prefix, suffix, null);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(tempFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
fos.write(byteArray);
fos.close();
return tempFile;
}
When I try to run it like this
File myFile = tiedostoService.createTempFile(tiedosto.getContent(), attachment.getFileName());
I get an IOException like this
java.io.IOException: Unable to create temporary file, C:\Users\ROSHAN~1\AppData\Local\Temp\kuva1068864619970584773image\png
at java.io.File$TempDirectory.generateFile(File.java:1921)
at java.io.File.createTempFile(File.java:2010)
From the stacktrace. it can be seen that it's trying to create a file like C:\Users\ROSHAN~1\AppData\Local\Temp\kuva1068864619970584773image\png
and not C:\Users\ROSHAN~1\AppData\Local\Temp\kuva1068864619970584773image.png
How can I fix this? I'd really appreciate any sort of help.
'image/png' is a Mime Type. See all MimeTypes in java here
Write a util which converts mimetype to file extension. Hopefully this will help.
I think there is an extra \ in your suffix string, could you try debug and see the actual value of the suffix?
I tried to run:
String suffix = "\\png";
and got the same error, but if I do
String suffix = ".png";
no error creating the temp file, notice that you need to add a dot in the suffix...
Related
I'm working on an app that needs to send an automatic email on button click. the problem I am currently have is that I need to read a json file and when I pass the path of the json stored in assets into into a new FileReader() I get a file not found Exception. here is how I am getting the path. (wondering if Uri.parse().toString is redundant):
private static final String CLIENT_SECRET_PATH =
Uri.parse("file:///android_asset/raw/sample/***.json").toString()
and here is the method I am passing it into:
sClientSecrets = GoogleClientSecrets
.load(jsonFactory, new FileReader(CLIENT_SECRET_PATH));
the json file that I am attemping to access is in my apps asset folder under the app root in android project directory (/app/assets/)
I am not sure what I am doing wrong here but I'm sure it is something simple. please help point me in the right direction.
You should not access the assets using direct file path.
The files are packed and the location will change on each device.
You need to use a helper function to get the assets path
getAssets().open()
See this post for more information.
Keep your file directly inside assets directory rather then raw-sample.
And then file path will be like this
private static final String CLIENT_SECRET_PATH =
Uri.parse("file:///android_asset/***.json").toString()
hope your problem will be solved..
You can use this function to get JSON string from assets and pass that string to the FileReader.
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getActivity().getAssets().open("yourfilename.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
#Rohit i was able to use the method you provided as a starting point. the only issue with it was that the gmail api that i am using requires a Reader as its parameter, not a string. here is what i did. and i am no longer getting filenotfoundexception. thank you very much.
public InputStreamReader getJsonStreamReader(String file){
InputStreamReader reader = null;
try {
InputStream in = getAssets().open(file);
reader = new InputStreamReader(in);
}catch(IOException ioe){
Log.e("launch", "error : " + ioe);
}
return reader;
}
I write with a java program into a file for further processing. This is the code for writing into the file:
FileOutputStream fos;
File f = new File(outputFilePath);
fos = new FileOutputStream(f);
final String R = "\r";
try {
fos.write((outputString + R).getBytes());
fos.flush();
fos.close();
} catch (IOException e) {
logger.error("fail..."+ e);
}
This works fine and after process I check with notepad++ the file and the right lines are in it. But if I want to use it with a perlscript (obj2opengl.pl) there comes an error. If I copy exactly that text into a new textfile manually with notepad++ it works. So my assumption is that there is somesthing wrong or bad in my java code. I tried already other encodings and so on... maybe anyone have an idea.
The error of the perl script says: "Illegal division by zero at obj2opengl.pl line 294".
That error not occured if I test it with the same text after copied it in a new textfile.
Try to change
final String R = "\r";
to
final String R = "\n";
you have to call close too FileOutputStream object:
fos.close();
i have a stupid question here i'm implementing upload button with vaadin and i want the users to upload only compressed files (.zip,.rar..), imake a search but i didn't find something useful :
so i tried to do this , i know it's not good solution because the user already uploaded the selected file :
#Override
public OutputStream receiveUpload(String filename, String mimeType) {
// Create upload stream
FileOutputStream fos = null; // Stream to write to
String fileName ;
String userHome = System.getProperty( "user.home" );
try {
// Open the file for writing.
file = new File(userHome+"/kopiMap/runtime/uploads/report/" + filename);
fileName= file.getName();
//Here i will get file extension
fos = new FileOutputStream(file);
} catch (final java.io.FileNotFoundException e) {
Notification.show(
"Could not open file<br/>", e.getMessage(),
Notification.TYPE_ERROR_MESSAGE);
return null;
}
return fos; // Return the output stream to write to
}
So how to do it before uploading
you can check the mimeType and if it is application/zip
#Override
public OutputStream receiveUpload(String filename, String mimeType) {
// Create upload stream
if(mimeType.equals("application/zip"))
//Here you can restrict
You can add this and it will work (all done by HTML 5 and most browser support now accept attribute) - this is example for .csv files:
upload.setButtonCaption("Import");
JavaScript.getCurrent().execute("document.getElementsByClassName('gwt-FileUpload')[0].setAttribute('accept', '.csv')");
I have a UTF-8 text file example.txt that contains:
c:/temp/file.txt
I read the file content using this method:
public static String fileToString(final File file, final String charset) throws AppServerException
{
final byte[] buffer = new byte[(int) file.length()];
FileInputStream fileInputStream = null;
try
{
fileInputStream = new FileInputStream(file);
fileInputStream.read(buffer);
}
catch (final FileNotFoundException e)
{
throw new AppServerException(e.getMessage());
}
catch (final IOException e)
{
throw new AppServerException(e.getMessage());
}
finally
{
FileHelper.close(fileInputStream);
}
try
{
return new String(buffer,charset);
}
catch (UnsupportedEncodingException e)
{
throw new AppServerException(e.getMessage());
}
}
Then I want to check if the file c:/temp/file.txt exists:
String content = fileToString("example.txt","UTF8");
File file = new File(content );
System.out.println(file.exists());
The exits() return false but the file actually exists.
If I change the encoding of example.txt to ANSI using notepad++, the exists() return true.
I already tried using:
"c:\temp\file.txt",
"c:\\temp\\file.txt",
"c:\\\\temp\\\\file.txt",
but without success.
I really need to use the file as UTF8. Do you have tips so the method exists() returns true?
Notepad++ probably puts a Byte Order Mark in front of the file. This is unnecessary for UTF-8 and Java does not interpret this sequence of three characters.
Either use an editor that does not use a Byte Order Mark or write the string in ANSI if your filename does not contain any non-ASCII characters.
Perhaps the file is not actually encoded as UTF-8. Can you print the actual byte values of the "\" characters in the file?
While you are at it: InputStream.read(byte[] b) is not guaranteed to read b.length bytes from the stream. You should be reading in a loop and checking the return value of the read() method in order to see how many bytes were actually read in each call.
I am using Eclipse. I want to read number of XML files from a directory. Each XML file contains multiple body tags. I want to extract values of all the body tags. My problem is I have to save each body tag value (text) in a separate .txt file and add these text files in another given directory. Can you plz help how can I create dynamically .txt file and add them in a specified directory?
Thanks in advance.
First specify directory path and name
File dir=new File("Path to base dir");
if(!dir.exists){
dir.mkdir();}
//then generate File name
String fileName="generate required fileName";
File tagFile=new File(dir,fileName+".txt");
if(!tagFile.exists()){
tagFile.createNewFile();
}
add import for java.io.File;
File f;
f=new File("myfile.txt");
if(!f.exists()){
f.createNewFile();
replace "myfile.txt" to path to file you needed and file will be created when you say
e.g. "c:\\somedir\\yourfile.txt"
It's not clear why you have mentioned the XML part. But it seems that you are able to get the text from XML file and wanted to write to separate text file.
Please go through this basic tutorial for creating, reading and writing files in Java: http://download.oracle.com/javase/tutorial/essential/io/file.html
Path logfile = ...;
//Convert the string to a byte array.
String s = ...;
byte data[] = s.getBytes();
OutputStream out = null;
try {
out = new BufferedOutputStream(logfile.newOutputStream(CREATE, APPEND));
...
out.write(data, 0, data.length);
} catch (IOException x) {
System.err.println(x);
} finally {
if (out != null) {
out.flush();
out.close();
}
}
Do something like this.
try {
//Specify directory
String directory = //TODO....
//Specify filename
String filename= //TODO....
// Create file
FileWriter fstream = new FileWriter(directory+filename+".txt");
BufferedWriter out = new BufferedWriter(fstream);
//insert your xml content here
out.write("your xml content");
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
} finally {
//Close the output stream
out.close();
}