I am trying to read file from a mount point in the server where I am deploying the java code. Part of the java code is as below:
public static String encodeFileToBase64Binary(String fileName) throws IOException {
File file = new File(fileName);
byte[] bytes = loadFile(file);
byte[] encoded = Base64.encodeBase64(bytes);
String encodedString = new String(encoded);
return encodedString;
}
But it is throwing ERROR:
Callout to java method "public static java.lang.String
encodebase64.EncodeBase64.encodeFileToBase64Binary(java.lang.String)
throws java.io.IOException" resulted in exception:
/data1/Test_Folder/EmailAttachment/AttachmentOSBTest.txt (No such file
or directory) java.io.FileNotFoundException:
/data1/Test_Folder/EmailAttachment/AttachmentOSBTest.txt (No such file
or directory)
I tried placing the file in {$user.home} in the server and then reading from that path and it is working. Reading from Mount point in server is failing. What extra should I specify in the code?
Related
I am converting an InputStream to file using below code snippet. This is creating file in temp location. But when I get PDF/Word/XLS as an inputstream. This is corrupting the file and I am unable to use this file object for other operations. I know I have to set content-type/Mime type. I tried giving the prefix and suffix matching my requirement but it didn't work.
public static final String PREFIX = "stream2file";
public static final String SUFFIX = ".tmp";
public static File stream2file (InputStream in) throws IOException {
final File tempFile = File.createTempFile(PREFIX, SUFFIX);
tempFile.deleteOnExit();
try (FileOutputStream out = new FileOutputStream(tempFile)) {
IOUtils.copy(in, out);
}
return tempFile;
}
I don't know what has to be added in this code snippet while creating the temporary file so that I can retrieve all the files without corrupting.
I'm using PhantomJS to do headless testing of a website. Since the exe will be bundled inside the jar file I decided to read it and write it to a temporary file so that I can access it normally via absolute path.
Here's code for converting an InputStream into a String referring to the new temporary file:
public String getFilePath(InputStream inputStream, String fileName)
throws IOException
{
String fileContents = readFileToString(inputStream);
File file = createTemporaryFile(fileName);
String filePath = file.getAbsolutePath();
writeStringToFile(fileContents, filePath);
return file.getAbsolutePath();
}
private void writeStringToFile(String text, String filePath)
throws FileNotFoundException
{
PrintWriter fileWriter = new PrintWriter(filePath);
fileWriter.print(text);
fileWriter.close();
}
private File createTemporaryFile(String fileName)
{
String tempoaryFileDirectory = System.getProperty("java.io.tmpdir");
File temporaryFile = new File(tempoaryFileDirectory + File.separator
+ fileName);
return temporaryFile;
}
private String readFileToString(InputStream inputStream)
throws UnsupportedEncodingException, IOException
{
StringBuilder inputStringBuilder = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream, "UTF-8"));
String line;
while ((line = bufferedReader.readLine()) != null)
{
inputStringBuilder.append(line);
inputStringBuilder.append(System.lineSeparator());
}
String fileContents = inputStringBuilder.toString();
return fileContents;
}
This works but when I'm trying to launch PhantomJS it'll give me an ExecuteException:
SERVERE: org.apache.commons.exec.ExecuteException: Execution failed (Exit value: -559038737. Caused by java.io.IOException: Cannot run program "C:\Users\%USERPROFILE%\AppData\Local\Temp\phantomjs.exe" (in directory "."): CreateProcess error=216, the version of %1 is not compatible with this Windows version. Check the system information of your computer and talk to the distributor of this software)
If I don't try to read PhantomJS out of the jar hence using a relative path it works fine. The question is how I can read and execute PhantomJS from within a jar file or at least get the workaround with reading and writing a new (temporary) file to work.
You can't execute a JAR entry, because a JAR is a zip file and operating systems don't support running executables from inside a zip file. They could in principle, but it would boil down to "copy the exe out of the zip and then run it".
The exe is getting corrupted because you're storing it in a String. Strings aren't binary data, they're UTF-16, which is why you can't read straight from an InputStream into a String--encoding conversion is required. Your code is reading the exe as UTF-8, converting it to UTF-16, then writing it back out with the default character set. Even if the default character set happens to be UTF-8 on your machine, this will result in mangled data because an exe isn't valid UTF-8.
Try this on for size. Java 7 introduced NIO.2, which (among other things), has a lot of convenience methods for common file operations. Including putting an InputStream into a file! I'm also using the temp file API, which will prevent collisions if multiple instances of your app are run at the same time.
public String getFilePath(InputStream inputStream, String prefix, String suffix)
throws IOException
{
java.nio.file.Path p = java.nio.file.Files.createTempFile(prefix, suffix);
p.toFile().deleteOnExit();
java.nio.file.Files.copy(inputStream, p, java.nio.file.StandardCopyOption.REPLACE_EXISTING);
return p.toAbsolutePath().toString();
}
My goal
I am trying to write simple objects (SimpleType) into files, so that the files can be loaded later and the objects recreated.
My setting
I am currently working in the NetBeans IDE (JDK8) on a Windows 7 machine. I don't think that should make a difference, though.
This is the type I would like to write into the file:
public class SimpleType implements Serializable {
boolean[] a;
boolean[] b;
}
This is the code I'm trying to get to run:
public class Test {
public static void main(String[] args)
throws IOException, ClassNotFoundException {
String fileName = "test.txt";
SimpleType foo = new SimpleType;
try (ObjectOutputStream out = new ObjectOutputStream(new
BufferedOutputStream(new FileOutputStream(fileName)))) {
out.writeObject(foo);
out.close();
}
}
}
My problem
The code compiles and runs, but always throws a FileNotFoundException:
Exception in thread "main" java.io.FileNotFoundException: test.txt (Access is denied)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
at java.io.FileOutputStream.<init>(FileOutputStream.java:101)
at Test.main(Test.java:33)
My attempts to fix it
According to the documentation, I would expect the file to be created if it doesn't exist already. I've thoroughly read the Javadoc for the method I attempt to use, an excerpt of which I cite here (emphasis mine):
public FileOutputStream(String name) throws FileNotFoundException
[...]
Parameters:
name - the system-dependent filename
Throws:
FileNotFoundException - if the file exists but is a directory rather
than a regular file, does not exist but cannot be created, or cannot
be opened for any other reason
SecurityException - if a security manager exists and its checkWrite
method denies write access to the file.
I am sure that I have read/write permissions in the directory; there is no existing file with the name test.txt so it cannot be locked by another program.
Changing fileName to an absolute path I am sure I can write into doesn't make any difference.
It is reproducible if file is in read-only mode. Can you try like this.
public static void main(String[] args) {
String fileName = "sampleObjectFile.txt";
SampleObject sampleObject = new SampleObject();
File file = new File(fileName);
file.setWritable(true); //make it writable.
try(ObjectOutputStream outputStream = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file)))){
outputStream.writeObject(sampleObject);
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
If you are writing the file on OS disk you need admin privileges. so avoid writing on OS disk.
Normally this is because you are trying to write on a location not allowed by your FileSystem (for example in Windows7 you cannot write a new file in c:). Try to investigate where the program is trying to write using procmon from Microsoft's SysInternals. Add a new filter (path contains test.txt) and see what happens.
Im currently debugging a webapp, where the user is supposed to upload a file which is then stored temporarily on the server and send via E-Mail to an administrator.
The app runs on a tomcat 8 in a linux server environment. The class from where the error occurs looks like follows:
#Service
public class BugReportBo implements IBugReportBo {
...
#Value("${app.temp.folder}")
private Resource temp;
...
private File byteArrayToFile(final byte[] lob, final String string) throws IOException {
final int locatorStartPos = 6;
String uri = temp.getURI().toString().substring(locatorStartPos);
//uri: var/lib/tomcat/webapps/prototype/res/temp/
//string: temp0.jpg
// convert array of bytes into file
File f = new File(uri + string);
FileOutputStream fileOuputStream = new FileOutputStream(uri + string);
fileOuputStream.write(lob);
fileOuputStream.close();
return f;
}
}
The error is thrown from FileOutputStream fileOuputStream = new FileOutputStream(uri + string);.
The Exception is a FileNotFoundException (message:"var/lib/tomcat/webapps/prototype/res/temp/temp0.jpg (Datei oder Verzeichnis nicht gefunden)").
Everything seems to be ok to me as the folder is where it is supposed to be and the path seems to be fine as well.
Any ideas?
var/lib/tomcat/webapps/prototype/res/temp/temp0.jpg
You forget the first '/', so the path is understand like a relative path, instead of an absolute path.
/var/lib/tomcat/webapps/prototype/res/temp/temp0.jpg
I'm trying to create some files dynamically in my Java project root. but I get the following error when I run the code.
java.io.FileNotFoundException: D:\POS_ALL\T_POS_NEWEST\TouchPosApplication\WebContent\zharaimages\279 (Access is denied)
Is it possible to write a file to the root project folder in Java? Here is the code used.
private void createImage(PosItemImageDTO imageDTO,String path) throws IOException {
byte[] bytes = imageDTO.getPosItemImage();
path = path + "\\";
if(bytes!=null && bytes.length>0){
OutputStream out = null;
// BufferedImage img = ImageIO.read(new ByteArrayInputStream(bytes));
File l = new File(path);
out = new BufferedOutputStream(new FileOutputStream(path));
out.write(bytes);
if (out != null) {
out.close();
}
}
}
Its because it seems like you are trying to open and read a directory here. Your file as you say it, doesn't have any extension specified so java takes it as a directory. use isFile() method to check for a file before opening. You can use listFiles() method to obtain files of the directory.
Please make sure path = path + "\\"; is a correct path. If there is a directory, the program will show you Access is denied. You should add some checks before open the file, just like if (l.isDirectory()).