Write Hexadecimal Data to File As it is? - java

I have block of hexadecimal data which i want to write in a file as it is.
Block
000100050000470040002E000000000099009900500000000000490067008D0000000000890081007600000000004C002F0027000000000200050000470040002E0000000000000D00590065006C006C006F00770020006F006C0069007600650000000099009900500000000000000D004F006C006900760065002000790065006C006C006F007700000000490067008D0000000000000D00440069007300740061006E007400200062006C00750065000000008900810076000000000000110050006500610072006C0020006D006F00750073006500200067007200650079000000004C002F00270000000000000F004D00610068006F00670061006E0079002000620072006F0077006E0000
Above block represent a Adobe .aco (stores a color palette) file .
Similar File opened in hex editor shows:-
On trying to write Given block using
Code
try {
File ACO = new File(f.getAbsolutePath(),"NameRandom.aco");
ACO.createNewFile();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(ACO)));
try {
writer.write(<-- Above Block -->);
} finally {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
But the above code shows different in hed Editor (as Following image)
I want to write Given block as it is in its current state in file.

You are getting a different hex code because you are writing the string in some encoding. If you wish to write such byte data first convert the data from string to byte[] and then write the bytes.
To convert see: Convert a string representation of a hex dump to a byte array using Java?

Related

saving h264 file in JAVA works, but in android it saves corrupted file

I am trying to save a stream of bytes in h264 format, to an h264 file.
I did it in JAVA, and the file is being saved and I can open it and see the video.
BUT, when I try the exact same code, in android, and I'm trying to save the file through the android device, the file is corrupted.
This is my code (both for android and for java):
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
File file = new File(path, "/" + "filename2.mp4");
FileOutputStream output2 = null;
try {
output2 = new FileOutputStream(file, true);
output2.write(my_stream.toByteArray());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
output2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
offcourse just the path is different in java and in the android version
Maybe because my_stream.toByteArray() is only one part of the whole video. Read the video stream in a loop and write it to the output stream chunk by chunk.
Alternatively there is this function that will do it for you:
Files.copy(videoInputStream, filePath, StandardCopyOptions.REPLACE_EXISTING);
Or if the input is a byte array:
Files.write(outputPath, bytes, StandardOpenOptions.WRITE,
StandardOpenOptions.CREATE_NEW,
StandardOpenOptions.CREATE);
Full documentation: https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#write(java.nio.file.Path,%20byte[],%20java.nio.file.OpenOption...)
https://docs.oracle.com/javase/7/docs/api/java/nio/file/StandardOpenOption.html

Reading and writing file in ISO-8859-1 encoding?

I have file encoded in ISO-8859-1. I'm trying to read it in as a single String, do some regex substitutions on it, and write it back out in the same encoding.
However, the resulting file I get always seems to be UTF-8 (according to Notepad++ at least), mangling some characters.
Can anyone see what I'm doing wrong here?
private static void editFile(File source, File target) {
// Source and target encoding
Charset iso88591charset = Charset.forName("ISO-8859-1");
// Read the file as a single string
String fileContent = null;
try (Scanner scanner = new Scanner(source, iso88591charset)) {
fileContent = scanner.useDelimiter("\\Z").next();
} catch (IOException exception) {
LOGGER.error("Could not read input file as a single String.", exception);
return;
}
// Do some regex substitutions on the fileContent string
String newContent = regex(fileContent);
// Write the file back out in target encoding
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(target), iso88591charset))) {
writer.write(newContent);
} catch (Exception exception) {
LOGGER.error("Could not write out edited file!", exception);
}
}
There is nothing actually wrong with your code. Notepad++ sees the file encoded in UTF-8 because on a basic level there is no difference between UTF-8 and the encoding you're trying to use. Only specific characters differ and some (a lot) are missing from ISO compared to UTF. You can read more here or by simply searching ISO-8859-1 vs UTF-8 in Google.
I've created a simple project with your code and tested it with characters that are different for the ISO encoding - the result is a file that IntelliJ (and probably Notepad++ as well - cannot easily check, I'm on Linux) recognizes as ISO-8859-1. Apart from that, I've added another class that makes use of new (JDK11) features from Files class. The new Scanner(source, charset) that you've used was added in JDK10, so I think that you may be using 11 already. Here's the simplified code:
private static void editFile(File source, File target) {
Charset charset = StandardCharsets.ISO_8859_1;
String fileContent;
try {
fileContent = Files.readString(source.toPath(), charset);
} catch (IOException exception) {
System.err.println("Could not read input file as a single String.");
exception.printStackTrace();
return;
}
String newContent = regex(fileContent);
try {
Files.writeString(target.toPath(), newContent, charset);
} catch (IOException exception) {
System.err.println("Could not write out edited file!");
exception.printStackTrace();
}
}
Feel free to clone the repository or check it on GitHub and use whichever code version you prefer.

Buffered writer writes memory trash on text file

My buffered writer is writting some randomly trash in my txt file. I use int nodes = Integer.valueOf(NODES_TEXT_FIELD.getText()); to store the value of one TextField that should only accept ints.
this is my writer:
private static void writeOnFile(BufferedWriter writer, int nodes){
try {
System.out.println(nodes);
System.out.println("Last check before write");
writer.write(nodes);
System.out.println(nodes);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Failed to write data on file");
e.printStackTrace();
}
}
My output:
2
Last check before write
2
and in the text file I found: '?' (which changes to another memory trash depending on what number you input
Anybody has any Idea of what might be wrong? I stuck here for 5 hours until now..
Because write() writes a character .
Writes a single character. The character to be written is contained in the 16 low-order bits of the given integer value; the 16 high-order bits are ignored.
Parameters:
c - int specifying a character to be written
You can use Writer#write(String):
writer.write(String.valueOf(nodes));
Try this:
Writer wr = new FileWriter("thefileToWriteTo.txt");
wr.write( String.valueOf(nodes) );
wr.close();
you can always extract the writing into a loop if that is what you are doing with your nodes or some kind of escaping, it would be more helpful if you explain what is it that you are actually trying to achieve by writing this to a file, as we might advise you on that.

Android-Writing to a file results in random characters

Argargarg.
I am trying to get information from a user input, then to write it to a system file. I get the input, and I call getBytes on it. It logs to the file something along the lines of "null" and random numbers after that. I tried getting it to a string, no luck there, it was a random chain of symbols
Here is the specific code:
TextView note_input=(TextView) findViewById(R.id.note_input);
FileOutputStream fos=null;
String newNote=note_input.getText().toString();
Log.w("Debug",newNote);
try {
fos=openFileOutput("currentNote",Context.MODE_APPEND);
} catch (FileNotFoundException e) {
//IT_SHOUD_NOT_EXIST
}
try {
Log.w("Debug",newNote.getBytes().toString());
fos.write(newNote.getBytes());
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I appreciate any help!
String.getBytes returns array of bytes, and when you try to do toString() you are actually writing it's pointer to string. You already have String change this line
Log.w("Debug",newNote.getBytes().toString());
into
Log.w("Debug",newNote);
and you will have proper Log output, and File should be written properly already.
Hope this helps and enjoy your work
Just a shot in the dark, but I notice you're calling getBytes() without specifying the character encoding. Unless your output file is the same character encoding as the system default encoding, you could easily get gibberish on the output.

writing to a file, but not just at the end

I want to write something to a file line by line.
I have the problem, that this process takes a lot of time and get canceld sometimes. The current version write the stuff to the file just at the end. Is it possible to write it to the file line by line?
E.g. if I abboard after line 4 (of 400) the file currently is empty. But I want to have the 4 line already in the file.
Here is my code:
String path = args[0];
String filename = args[1];
BufferedReader bufRdr = // this does not matter
BufferedWriter out = null;
FileWriter fstream;
try {
fstream = new FileWriter(path + "Temp_" + filename);
out = new BufferedWriter(fstream);
} catch (IOException e) {
System.out.println(e.toString());
}
String line = null;
try {
while ((line = bufRdr.readLine()) != null) {
// HERE I'm doing the writing with out.write
out.write(...);
}
} catch (IOException e) {
System.out.println(e.toString());
}
try {
out.close();
} catch (IOException e) {
System.out.println(e.toString());
}
Use the flush function when you want to make sure the data that is already been written to the writer gets into the file
out.flush()
Try out.flush() after out.write(...)
Use out.flush() after calling out.write(...).
Considering the java documentation FileWriter, you can directly write things to a file using the FileWriter, without using a BufferedWriter.
Also, as pointed out, you need to flush your datas before closing your buffer. The function write only fill your buffer, but it doesn't write to the file on the disk. This operation is done by using flush or close (to write the current content of the buffer to the disk). The difference between these two functions is that flush let's you write things after and close closes the stream definitely.
The data you write to the buffer normally will not actually be written until out.flush() or out.close() is closed. so for your requirement you should use out.flush();

Categories

Resources