Hello experts, please i need help with this code, i created it to view hex of files, but it doesn't read large files because it stores the data in memory, which in turn gives out"OutOfMemory" error. I want to be able to view the hex like this
http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.github.javadev%22%20AND%20a%3A%22hexeditor%22. It can view files of up to 9 exabytes as it claims;
1. how can i change my code to do the same?
2. What do i need to add or remove or change please?
I'm actually a newbie so if you'll help me with code please some explanation will be good i don't mean to be rude or if i'm asking too much please forgive. Thanks
<pre>import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import javax.swing.JFileChooser;
public class HexViewer {
public static void main(String[] args) throws FileNotFoundException, IOException {
InputStream is = null;
JFileChooser open = new JFileChooser();
open.showOpenDialog(null);
File f = open.getSelectedFile();
is = new BufferedInputStream(new FileInputStream(f));
int bytesCounter = 0;
int value;
StringBuilder set = new StringBuilder();
StringBuilder sbResult = new StringBuilder();
while ((value = is.read()) != -1) {
set.append(String.format("%02X ", value));
if (bytesCounter == 90) {
sbResult.append(set).append("\n");
bytesCounter = 0;
} else {
bytesCounter++;
}
System.out.print(set);
set.setLength(0);
}
if (bytesCounter != 0) {
for (; bytesCounter < 90; bytesCounter++) {
set.append(" ");
}
sbResult.append(set).append("\n");
}
}
}
What I have tried:
I used byte[] to read the file in chunks but it doesn't write the hex
<pre lang="java"><pre>import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import javax.swing.JFileChooser;
public class HexViewer {
public static void main(String[] args) throws FileNotFoundException, IOException {
InputStream is = null;
JFileChooser open = new JFileChooser();
open.showOpenDialog(null);
File f = open.getSelectedFile();
is = new BufferedInputStream(new FileInputStream(f));
int bytesCounter = 0;
byte[] buffer= new byte[1024];
int value;
StringBuilder set = new StringBuilder();
StringBuilder sbResult = new StringBuilder();
while ((value = is.read(buffer)) != -1) {
set.append(String.format("%02X ", value));
if (bytesCounter == 90) {
sbResult.append(set).append("\n");
bytesCounter = 0;
} else {
bytesCounter++;
}
System.out.print(set);
set.setLength(0);
}
if (bytesCounter != 0) {
for (; bytesCounter < 90; bytesCounter++) {
set.append(" ");
}
sbResult.append(set).append("\n");
}
}
}
I also check this hex editor
http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.github.javadev%22%20AND%20a%3A%22hexeditor%22 , but when reading through the source code i can't find out where or how the author accomplished it.