Saving an image array to a file - java

I have an array that looks like
String image = obj.getString("data");
[255,216,255,224,0,16,74,70,73,70,0,1,1,0,0,1,0,1,0,0, ....]// this is what image contains.
I try to convert it to a byte array by
byte[] bytes = image.getBytes();
Then I tried saving it with
File file = new File(Environment.getExternalStorageDirectory(), "DirImage/test.jpg");
FileOutputStream fos = new FileOutputStream(file);
fos.write(bytes);
fos.flush();
fos.close();
The file gets written but I cannot se the image.shows me a broken file.

First determine the number of bytes you need. So the amount of decimal values contained in the string. Then declare a byte array like byte bytes[] = new byte[amount];. You could also split that string in a string array first. String parts [] = image.split(",");. parts.length would tell 'amount'.
Then loop throught the parts and convert one by one the parts string to a byte.

I never worked directly with JPEG before,but i think that you need to specify some info at the beginning of the file,instead of outright outputting raw color values,try googling for jpeg structure.

Related

convert portion of byte array values to String

I have loaded the entire file into a byte[] array using following code:
byte[] data = Files.readAllBytes(path);
Now i would like to get the first 120 characters as String and any string info from from index and to index.
Could you please let me know how to do it?
Thanks.
Sounds like you're just looking for this constructor:
String text = new String(data, 0, 120, StandardCharsets.UTF_8);
(Always specify the encoding explicitly when converting between binary and text forms.)

write content in a byte array to a file and read the byte from file back to byte array

How can write content in a byte array to a file and read the byte from file back to byte array without changing the content written before. in java
There are two methods for exactly this, in Files
final Path path myFile = Paths.get("path","to","file");
final byte[] toWrite = ...
Files.write(myFile, toWrite, StandardOpenOption.CREATE_NEW);
final byte[] read = Files.readAllBytes(myFile);
assert Arrays.equals(toWrite, read);

Extract tar.gz file in memory in Java

I'm using the Apache Compress library to read a .tar.gz file, something like this:
final TarArchiveInputStream tarIn = initializeTarArchiveStream(this.archiveFile);
try {
TarArchiveEntry tarEntry = tarIn.getNextTarEntry();
while (tarEntry != null) {
byte[] btoRead = new byte[1024];
BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(destPath)); //<- I don't want this!
int len = 0;
while ((len = tarIn.read(btoRead)) != -1) {
bout.write(btoRead, 0, len);
}
bout.close();
tarEntry = tarIn.getNextTarEntry();
}
tarIn.close();
}
catch (IOException e) {
e.printStackTrace();
}
Is it possible not to extract this into a seperate file, and read it in memory somehow? Maybe into a giant String or something?
You could replace the file stream with a ByteArrayOutputStream.
i.e. replace this:
BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(destPath)); //<- I don't want this!
with this:
ByteArrayOutputStream bout = new ByteArrayOutputStream();
and then after closing bout, use bout.toByteArray() to get the bytes.
Is it possible not to extract this into a seperate file, and read it in memory somehow? Maybe into a giant String or something?
Yea sure.
Just replace the code in the inner loop that is openning files and writing to them with code that writes to a ByteArrayOutputStream ... or a series of such streams.
The natural representation of the data that you read from the TAR (like that) will be bytes / byte arrays. If the bytes are properly encoded characters, and you know the correct encoding, then you can convert them to strings. Otherwise, it is better to leave the data as bytes. (If you attempt to convert non-text data to strings, or if you convert using the wrong charset/encoding you are liable to mangle it ... irreversibly.)
Obviously, you are going to need to think through some of these issues yourself, but basic idea should work ... provided you have enough heap space.
copy the value of btoread to a String like
String s = String.valueof(byteVar);
and goon appending the byte value to the string untill end of the file reaches..

Converting Binary String into byte and not char while writing to file

I want to write the file as byte only and not the character.
String binaryString = "10110101"
I am using
byte mybyte = Byte.parseByte(binaryString,2);
I want to write this converted byte into the file as a byte and not the character.
I am using :
FileOutputStream fos1 = new FileOutputStream(new File("output"));
fos.write(mybyte);
But after write, when I see the files the byte is actually written as the characters.
Is I am doing something wrong in conversion ? How to make it write as byte and not char ?
Edit:
Like for the String 101101010111001011111000 (taking 8 bits at a time and then writing to the file) : it is converted to "Z9|".
You actually write the binary data 10110101 to the file, but when you open that file in a text editor it will be displayed as a character.
If you want to write text that represent the given number (e.g. in decimal form), use a Writer:
FileOutputStream fos1 = new FileOutputStream(new File("output"));
OutputStreamWriter w = new OutputStreamWriter(fos1, StandardCharsets.UTF_8);
w.write(""+mybyte); // ""+mybyte creates a string with the decimal representation of mybyte

Java Charset InputStreamReader, File Channel Differences

I'm trying to read a (Japanese) file that is encoded as a UTF-16 file.
When I read it using an InputStreamReader with a charset of 'UTF-16" the file is read correctly:
try {
InputStreamReader read = new InputStreamReader(new FileInputStream("JapanTest.txt"), "UTF-16");
BufferedReader in = new BufferedReader(read);
String str;
while((str=in.readLine())!=null){
System.out.println(str);
}
in.close();
}catch (Exception e){
System.out.println(e);
}
However, when I use File Channels and read from a byte array the Strings aren't always converted correctly:
File f = new File("JapanTest.txt");
fis = new FileInputStream(f);
channel = fis.getChannel();
MappedByteBuffer buffer = channel.map( FileChannel.MapMode.READ_ONLY, 0L, channel.size());
buffer.position(0);
int get = Math.min(buffer.remaining(), 1024);
byte[] barray = new byte[1024];
buffer.get(barray, 0, get);
CharSet charSet = Charset.forName("UTF-16");
//endOfLinePos is a calculated value and defines the number of bytes to read
rowString = new String(barray, 0, endOfLinePos, charSet);
System.out.println(rowString);
The problem I've found is that I can only read characters correctly if the MappedByteBuffer is at position 0. If I increment the position of the MappedByteBuffer and then read a number of bytes into a byte array, which is then converted to a string using the charset UTF-16, then the bytes are not converted correctly. I haven't faced this issue if a file is encoded in UTF-8, so is this only an issue with UTF-16?
More Details:
I need to be able to read any line from the file channel, so to do this I build a list of line ending byte positions and then use those positions to be able to get the bytes for any given line and then convert them to a string.
The code unit of UTF-16 is 2 bytes, not a byte like UTF-8. The pattern and single byte code unit length makes UTF-8 self-synchronizing; it can read correctly at any point and if it's a continuation byte, it can either backtrack or lose only a single character.
With UTF-16 you must always work with pairs of bytes, you cannot start reading at an odd byte or stop reading at an odd byte. You also must know the endianess, and use either UTF-16LE or UTF-16BE when not reading at the start of the file, because there will be no BOM.
You can also encode the file as UTF-8.
Possibly, the InputStreamReader does some transformations the normal new String(...) does not. As a work-around (and to verify this assumption) you could try to wrap the data read from the channel like new InputStreamReader( new ByteArrayInputStream( barray ) ).
Edit: Forget that :) - Channels.newReader() would be the way to go.

Categories

Resources