Apache Jena saving ttl file - java

Hi I have created a model with Apache Jena and can output it this way:
model.write(System.out, "Turtle");
Is it possible to save the turtle file as .ttl on disk?

To write your model to a file you just pass an OutputStream instead of System.out, like this:
OutputStream out = new FileOutputStream("output-model.ttl");
RDFDataMgr.write(out, model, Lang.TURTLE);
or:
OutputStream out = new FileOutputStream("output-model.ttl");
model.write(out, Lang.TURTLE);
Don't forget to close your stream once the file is fully written.

Related

Get Part or stream of uploading file

How to get part or stream of file without using request, just file in a form using hibernate .
Nb : I can't use request.getPart();
The answer is FileInputStream stream = new FileInputStream(file);

Write Object from List to File, using ObjectOutputStream

I'm trying to write the content of a list (object) to disk using ObjectOutputStream.
This is the relevant code:
//Input Filetype is .xlsx with an embedded File (also .xlsx), Output Filetype should be .xlsx (Type of embedded File)
//This code should save the embedded File to D:\\...
List<HSSFObjectData> extrList = new ArrayList<HSSFObjectData>();
HSSFWorkbook embeddedWorkbook = new HSSFWorkbook(pPart.getInputStream());
extrList = embeddedWorkbook.getAllEmbeddedObjects();
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\scan_temp\\emb.xlsx"));
oos.writeObject(extrList);
oos.flush();
oos.close();
This code creates a file called emb.xlsx, but the content is not what I expected. If I try to open using notepad, it's something like:
¬í sr java.util.ArrayListxÒ™Ça I sizexp w x
What am I doing wrong here? Thanks for any help.
What am I doing wrong here?
You are doing several things wrong:
You are misusing the .xlsx extension for a file of serialized objects. That extension is for Excel spreadsheets in XML format. You should use something like .bin, .data, .ser, etc.
You are using Serialization when you should be using the I/O facilities built into POI.
You are trying to read a binary file with a text editor.
You are redundantly callling flush() before close().
If anyone else is trying the same thing as I did, use the following code (works!):
HSSFWorkbook embeddedWorkbook = new HSSFWorkbook(InputStream);
FileOutputStream fileOut = new FileOutputStream("/outputfilepath.xls");
embeddedWorkbook.write(fileOut);
fileOut.close();
Don't try to get the embedded objects into a list. Just use .write()and that's all. :-)

NIO GZIP compression and copying of files

I was using FileChannel and FileInputStream to do a simple file copying from File fromFile to File toFile.
The code is basically like this:
source = new FileInputStream(fromFile).getChannel();
destination = new FileOutputStream(toFile, false).getChannel(); // overwrite
destination.transferFrom(source, 0, source.size());
where fromFile and toFile are proper File objects.
Now, instead of copying from fromFile directly, i wanted to compress its content using GZIP (found in Java libraries) and then copy to toFile. Also reversely, when I transfer back from toFile, I would like to decompress it as well.
I was wondering is there a simple way like
source = new GZIPCompressInputStream(new FileInputStream(fromFile)).getChannel();
or
source = new GZIPDecompressInputStream(new FileInputStream(fromFile)).getChannel();
and all the rest of code remain unchanged. Do you have any suggestion on the cleanest solution to this?
Thanks..
You could wrap your FileInputStream in a GZIPInputStream like so:
InputStream input = new GZIPInputStream(yourCompressedInput);
For compressing when writing, you should use the GZIPOutputStream.
Good luck.

How to create a new java.io.File in memory? [duplicate]

This question already has answers here:
How to read file from ZIP using InputStream?
(7 answers)
Closed 1 year ago.
How can I create new File (from java.io) in memory, not on the hard disk?
I am using the Java language. I don't want to save the file on the hard drive.
I'm faced with a bad API (java.util.jar.JarFile). It's expecting File file of String filename. I have no file (only byte[] content) and can create temporary file, but it's not beautiful solution. I need to validate the digest of a signed jar.
byte[] content = getContent();
File tempFile = File.createTempFile("tmp", ".tmp");
FileOutputStream fos = new FileOutputStream(tempFile);
fos.write(archiveContent);
JarFile jarFile = new JarFile(tempFile);
Manifest manifest = jarFile.getManifest();
Any examples of how to achieve getting manifest without creating a temporary file would be appreciated.
How can I create new File (from java.io) in memory , not in the hard disk?
Maybe you are confusing File and Stream:
A File is an abstract representation of file and directory pathnames. Using a File object, you can access the file metadata in a file system, and perform some operations on files on this filesystem, like delete or create the file. But the File class does not provide methods to read and write the file contents.
To read and write from a file, you are using a Stream object, like FileInputStream or FileOutputStream. These streams can be created from a File object and then be used to read from and write to the file.
You can create a stream based on a byte buffer which resides in memory, by using a ByteArrayInputStream and a ByteArrayOutputStream to read from and write to a byte buffer in a similar way you read and write from a file. The byte array contains the "File's" content. You do not need a File object then.
Both the File... and the ByteArray... streams inherit from java.io.OutputStream and java.io.InputStream, respectively, so that you can use the common superclass to hide whether you are reading from a file or from a byte array.
It is not possible to create a java.io.File that holds its content in (Java heap) memory *.
Instead, normally you would use a stream. To write to a stream, in memory, use:
OutputStream out = new ByteArrayOutputStream();
out.write(...);
But unfortunately, a stream can't be used as input for java.util.jar.JarFile, which as you mention can only use a File or a String containing the path to a valid JAR file. I believe using a temporary file like you currently do is the only option, unless you want to use a different API.
If you are okay using a different API, there is conveniently a class in the same package, named JarInputStream you can use. Simply wrap your archiveContent array in a ByteArrayInputStream, to read the contents of the JAR and extract the manifest:
try (JarInputStream stream = new JarInputStream(new ByteArrayInputStream(archiveContent))) {
Manifest manifest = stream.getManifest();
}
*) It's obviously possible to create a full file-system that resides in memory, like a RAM-disk, but that would still be "on disk" (and not in Java heap memory) as far as the Java process is concerned.
You could use an in-memory filesystem, such as Jimfs
Here's a usage example from their readme:
FileSystem fs = Jimfs.newFileSystem(Configuration.unix());
Path foo = fs.getPath("/foo");
Files.createDirectory(foo);
Path hello = foo.resolve("hello.txt"); // /foo/hello.txt
Files.write(hello, ImmutableList.of("hello world"), StandardCharsets.UTF_8);
I think temporary file can be another solution for that.
File tempFile = File.createTempFile(prefix, suffix, null);
FileOutputStream fos = new FileOutputStream(tempFile);
fos.write(byteArray);
There is a an answer about that here.

How to create a java.io.File from a ByteArrayOutputStream?

I'm reading a bunch of files from an FTP. Then I need to unzip those files and write them to a fileshare.
I don't want to write the files first and then read them back and unzip them. I want to do it all in one go. Is that possible?
This is my code
FTPClient fileclient = new FTPClient();
..
ByteArrayOutputStream out = new ByteArrayOutputStream();
fileclient.retrieveFile(filename, out);
??????? //How do I get my out-stream into a File-object?
File file = new File(?);
ZipFile zipFile = new ZipFile(file,ZipFile.OPEN_READ);
Any ideas?
You should use a ZipInputStream wrapped around the InputStream returned from FTPClient's retrieveFileStream(String remote).
You don't need to create the File object.
If you want to save the file you should pipe the stream directly into a ZipOutputStream
ByteArrayOutputStream out = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(out);
// do whatever with your zip file
If, instead, you want to open the just retrieved file work with the ZipInputStream:
new ZipInputStream(fileClient.retrieveFileStream(String remote));
Just read the doc here and here
I think you want:
ZipInputStream zis = new ZipInputStream( new ByteArrayInputStream( out.toByteArray() ) );
Then read your data from the ZipInputStream.
As others have pointed out, for what you are trying to do, you don't need to write the downloaded ZIP "file" to the file system at all.
Having said that, I'd like to point out a misconception in your question, that is also reflected in some of the answers.
In Java, a File object does no really represent a file at all. Rather, it represents a file name or *path". While this name or path often corresponds to an actual file, this doesn't need to be the case.
This may sound a bit like hair-splitting, but consider this scenario:
File dir = new File("/tmp/foo");
boolean isDirectory = dir.isDirectory();
if (isDirectory) {
// spend a long time computing some result
...
// create an output file in 'dir' containing the result
}
Now if instances of the File class represented objects in the file system, then you'd expect the code that creates the output file to succeed (modulo permissions). But in fact, the create could fail because, something deleted the "/tmp/foo", or replaced it with a regular file.
It must be said that some of the methods on the File class do seem to assume that the File object does correspond to a real filesystem entity. Examples are the methods for getting a file's size or timestamps, or for listing the names in a directory. However, in each case, the method is specified to throw an exception if the actual file does not exist or has the wrong type for the operation requested.
Well, you could just create a FileOutputStream and then write the data from that:
FileOutputStream fos = new FileOutputStream(filename);
try {
out.writeTo(fos);
} finally {
fos.close();
}
Then just create the File object:
File file = new File(filename);
You need to understand that a File object doesn't represent any real data on disk - it's just a filename, effectively. The file doesn't even have to exist. If you want to actually write data, that's what FileOutputStream is for.
EDIT: I've just spotted that you didn't want to write the data out first - but that's what you've got to do, if you're going to pass the file to something that expects a genuine file with data in.
If you don't want to do that, you'll have to use a different API which doesn't expect a file to exist... as per Qwerky's answer.
Just change the ByteArrayOutputStream to a FileOutputStream.

Categories

Resources