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
Related
File f = new File("even.txt");
FileOutputStream fo = new FileOutputStream(f);
int a = 2;
fo.write(a);
fo.close();
Whenever I run this program and open the "even.txt" file, all I'm able to see is a hash symbol in the file. This doesn't happen when I work with a string.
File f = new File("even.txt");
FileOutputStream fo = new FileOutputStream(f);
String s = "2";
byte b[] = s.getBytes();
fo.write(b);
fo.close();
I don't understand why this happens.
You have to write String. You can try one of:
wr.write("222");
wr.write(new Integer(222).toString());
wr.write( String.valueOf(222) );
it's because the method fo.write(int) doesn't actually write the int itself, it writes the character represented by the int in the encoding specified (utf-8 if not specified).
What you have to understand is
int a = 2;
fo.write(a); //This line write the byte 0x02 to the inputstream because that is the binary representation of the digit 2
String s = "2";
byte b[] = s.getBytes();
fo.write(b); //This one write 0x32 to the inputstream because that is the ascii respresentation of the character "2" which is return by getBytes() from the string class
you can check the difference between the two file the code generate in an hex editor
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.
I need to encode/decode pdf file into Base64 format.
So I read file from disk into String(because I will receive file in String Base64 format in future);
String pdfString = IOUtils.toString(new FileInputStream(new
File("D:\\vrpStamped.pdf")));
byte[] encoded = Base64.encodeBase64(pdfString.getBytes());
byte[] newPdfArray = Base64.decodeBase64(encoded);
FileOutputStream imageOutFile = new FileOutputStream(
"D:\\1.pdf");
imageOutFile.write(newPdfArray);
imageOutFile.close();
imageOutFile.flush();
So my D:\\1.pdf doesnt opens in AdobeReader, but if I read file straight to byte array, using IOUtils.toByteArray(..) instead ,all works fine and my D:\\1.pdf file sucessfuly opens in Adobe Reader:
byte[] encoded = Base64.encodeBase64(IOUtils.toByteArray(new FileInputStream(new File("D:\\vrpStamped.pdf"))););
It seems to me thath IOUtils.toString(..) change something inside file content. So how can I convert file to String with not content breaking?
How to encode a pdf...
byte[] bytes = IOUtils.toByteArray(new FileInputStream(new File("/home/fschaetz/test.pdf")));
byte[] encoded = Base64.encode(bytes);
String str = new String(encoded);
...now do something with this encoded String, for example, send it via a Rest service.
And now, if you receive an encoded String, you can decode and save it like this...
byte[] decoded = Base64.decode(str.getBytes());
FileOutputStream output = new FileOutputStream(new File("/home/fschaetz/result.pdf"));
output.write(decoded);
output.close();
Works perfectly fine with all files, not limited to images or pdfs.
What your example is doing is...
Read the pdf into a String (which pretty much destroys the data, since you are reading binary data into a String)
Encode this spring (which is in all likelyhood not a valid representation of the original pdf anymore)
Decode it and save it to disk
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);
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.