Reputation: 8702
I'm having a problem while converting a gif image to a base 64 string.
When I converts it, the code adds me like 100,000 AAAAAA whereas the image is really small!
Here is my code:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.util.ArrayList;
public class Main
{
public static void main(String[] args)
{
try
{
FileWriter fstream = new FileWriter("./out.txt");
BufferedWriter out = new BufferedWriter(fstream);
File folder = new File("./flags/");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
Main.readFile(out, listOfFiles[i]);
}
}
out.close();
System.out.println("Done");
}
catch (Exception e) {}
}
public static void readFile(BufferedWriter out, File file)
{
try
{
byte[] byteArray = new byte[102400];
FileInputStream fis = new FileInputStream(file);
String base64String;
int bytesRead = 0;
while ((bytesRead = fis.read(byteArray)) != -1)
{
new String(byteArray, 0, bytesRead);
base64String = Base64.encode(byteArray);
out.write("public static ImageIcon getFlag" + file.getName() + "()");
out.newLine();
out.write("{");
out.newLine();
ArrayList<String> array = Main.cut(base64String);
out.write("return Utils.toImage(\"" + array.get(0) + "\"");
for (int i=1; i<array.size()-1; i++)
{
out.write("<tab>+\"" + array.get(i) + "\"");
}
out.write("<tab>\"" + array.get(array.size() - 1) + "\");");
out.newLine();
out.write("}");
out.newLine();
out.newLine();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static ArrayList<String> cut(String in)
{
ArrayList<String> array = new ArrayList<String>();
while (in.length() > 76)
{
array.add( in.substring(0, 77) );
in = in.substring(77);
}
return array;
}
}
Basicaly, it writes in a text file out.txt
a bunch of java methods with the base 64 code inside.
Here is a (small) part of the output:
return Utils.toImage("R0lGODlhEAALANUAANPTAPZva/n5AfLySPz8iYqY3O01NgoksbGZa+kYGOskJKi05vb2XZ+r4+05O"<tab>+"Pv7eO3tKPv7bZak4dSvebC76tC2iPNISPX1UMkAAMm6U/NWTeYAAF5y1LqlevNaWpSh3e7uQ+1CQt"<tab>+"gAAKOv5Vds1C1I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AAA"<tab>+"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"<tab>+"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"<tab>+"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"<tab>+"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"<tab>+"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"<tab>+"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"<tab>+"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"<tab>+"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"<tab>+"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"<tab>
Thanks.
Edit: I'm using the base64 code from this question: https://stackoverflow.com/a/4265472/1295422
Upvotes: 24
Views: 107932
Reputation: 1388
I realize that this is an old question but perhaps someone will find my code sample useful. This code encodes a file in Base64 then decodes it and saves it in a new location.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import org.apache.commons.codec.binary.Base64;
public class Base64Example {
public static void main(String[] args) {
Base64Example tempObject = new Base64Example();
// convert file to regular byte array
byte[] codedFile = tempObject.convertFileToByteArray("your_input_file_path");
// encoded file in Base64
byte[] encodedFile = Base64.encodeBase64(codedFile);
// print out the byte array
System.out.println(Arrays.toString(encodedFile));
// print the encoded String
System.out.println(encodedFile);
// decode file back to regular byte array
byte[] decodedByteArray = Base64.decodeBase64(encodedFile);
// save decoded byte array to a file
boolean success = tempObject.saveFileFromByteArray("your_output_file_path", decodedByteArray);
// print out success
System.out.println("success : " + success);
}
public byte[] convertFileToByteArray(String filePath) {
Path path = Paths.get(filePath);
byte[] codedFile = null;
try {
codedFile = Files.readAllBytes(path);
} catch (IOException e) {
e.printStackTrace();
}
return codedFile;
}
public boolean saveFileFromByteArray(String filePath, byte[] decodedByteArray) {
boolean success = false;
Path path = Paths.get(filePath);
try {
Files.write(path, decodedByteArray);
success = true;
} catch (Exception e) {
e.printStackTrace();
}
return success;
}
}
Upvotes: 0
Reputation: 11234
You can create a large array and then copy it to a new array using System.arrayCopy
int contentLength = 100000000;
byte[] byteArray = new byte[contentLength];
BufferedInputStream inputStream = new BufferedInputStream(connection.getInputStream());
while ((bytesRead = inputStream.read()) != -1)
{
byteArray[count++] = (byte)bytesRead;
}
byte[] destArray = new byte[count];
System.arraycopy(byteArray, 0, destArray , 0, count);
destArray will contain the information you want
Upvotes: 0
Reputation: 11234
You can use the file Object to get the length of the file to initialize your array:
int length = Long.valueOf(file.length()).intValue();
byte[] byteArray = new byte[length];
Upvotes: 0
Reputation: 5140
Late GraveDig ... Just constrain your byte array to the file size.
FileInputStream fis = new FileInputStream( file );
byte[] byteArray= new byte[(int) file.length()];
Upvotes: 0
Reputation: 76171
To begin with, this line of code:
while ((bytesRead = fis.read(byteArray)) != -1)
is equivalent to
while ((bytesRead = fis.read(byteArray, 0, byteArray.length)) != -1)
So it's writing into the byteArray from offset 0, rather than from where you wrote to before.
You need something like this:
int offset = 0;
int bytesRead = 0;
while ((bytesRead = fis.read(byteArray, offset, byteArray.length - offset) != -1) {
offset += bytesRead;
}
After you have read the data (bytes) in then, you can convert it to Base64.
There are bigger problems though - you're using a fixed size array, so files that are too big won't be converted correctly, and the code is tricker because of it too.
I would ditch the byte array and go with something like this:
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// commons-io IOUtils
IOUtils.copy(fis, buffer);
byte [] data = buffer.toByteArray();
Base64.encode(data);
Or condense it further as Thilo has with FileUtils.
Upvotes: 5
Reputation: 262464
byte[] byteArray = new byte[102400];
base64String = Base64.encode(byteArray);
That code will encode 102400 bytes, no matter how much data you actually use in the array.
while ((bytesRead = fis.read(byteArray)) != -1)
You need to use the value of bytesRead somewhere.
Also, this may not read the whole file into the array in one go (it only reads as much as is in the I/O buffer), so your loop will probably not work, you may end up with half an image in your array.
I'd use Apache Commons IOUtils here:
Base64.encode(FileUtils.readFileToByteArray(file));
Upvotes: 52
Reputation: 32286
new String(byteArray, 0, bytesRead);
does not modify the array. You need to use System.arrayCopy
to trim the array to the actual data size. Otherwise you are processing all 102400 bytes most of which are zeros.
Upvotes: 1
Reputation: 78795
The line
base64String = Base64.encode(byteArray);
converts the full array (102400 bytes) to Base64, not just the number of bytes you have read. You need to pass it the numbers of bytes.
Upvotes: 2