Jave InputStream convert to Base64 String not able to open file - java

I am using an InputStream that is PDF file that needs to be able to converted to a Base64 string. The Base64 string is not correct format because when I decode the PDF file will not open. Is there a better way to do this?
PDFString = fromStream(is);
String encoded = DatatypeConverter.printBase64Binary(PDFString.getBytes());
public static String fromStream(InputStream in) throws IOException
{
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder out = new StringBuilder();
String newLine = System.getProperty("line.separator");
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
out.append(newLine);
}
return out.toString();
}

Related

How to decompress invocation API response In Java?

I want to decompress an API response (header : Accept-encoding=gzip).
Here are the lines I tried but always failed due to:
java.util.zip.ZipException: Not in GZIP format
String entity = response.readEntity(String.class);
// When I print "entity" I will get Compress message as below:
��{o�ʒ��
���c^MC��������ut4"�ms���fWGگ�_o?�V�G�ę�=�PF�3��i�������ɚ���G�[�eEA����$��M�(�rW�nk��97�m�r��6�$�$T�a^ZaIj�"�5U�4�����4:oW�C{�-��A�c0�hސ�*l���JP�ƚ.������t�
}ˏ�r�kIxjk��!���m�0��Z�9 ���r[�����6!٦^fQ�X_d)hބe���m��\RP�Y��Xg�:�F�IEE�5]U��f�\jϋ�?N�ߖ�<�κ;�+��j�xQ�{����40�]4N�NOib�=o(r�mL�rLϱ�>Rۖ�l4
{2jʁk��f�*�љw��a�l���������^�V�a�ӱ���w[2�V>n��'��n���;�ȧ�#�p-ch}<>�9>�IB�~X��X���=��lz9)H��2#O?�R����*�����q�c�V�t����c�ܩ<��A��[���4
��
byte[] input = entity.getBytes();
// helper method
public static String decompress(byte[] compressed) throws IOException {
ByteArrayInputStream bis = new ByteArrayInputStream(compressed);
// Always failed at "GZIPInputStream" line due to java.util.zip.ZipException: Not in GZIP format
GZIPInputStream gis = new GZIPInputStream(bis);
BufferedReader br = new BufferedReader(new InputStreamReader(gis, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line;
while((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
gis.close();
bis.close();
return sb.toString();
}

How To Read Second Line In Text With Java

I am trying to create a simple command line program that will determine if a playlist is a media playlist or master based on the tag returned. Unfortunately both type of playlist first line tags are the same so I was wondering is their a way I could adjust my code to read the text starting at the second line?
private static String getPlaylistUrl(String theUrl) throws
FileNotFoundException, MalformedURLException, IOException{
String content = "";
//Creates a url variable
URL url = new URL(theUrl);
//Cretes a urlConnection variable
URLConnection urlConnection = (HttpURLConnection) url.openConnection();
//Wraps the urlConnection in a BufferedReader
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
content += line + "\n";
}
bufferedReader.close();
return content;
}
Just read the first line before the loop starts.
private static String getPlaylistUrl(String theUrl) throws IOException {
try (InputStream is = new URL(theUrl).openConnection().getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
Stream<String> stream = reader.lines()) {
return stream
// skip the first line
.skip(1)
// join all other lines using a new line delimiter
.collect(Collectors.joining("\n"));
}
}
Skip the header like this
String line;
bool IsHeader=true;
while ((line = bufferedReader.readLine()) != null) {
if (IsHeader){
IsHeader=false; //skip header..
}else{
content += line + "\n";
}
}
bufferedReader.close();

Android Java String to Blob

I am trying to convert a string to blob like this:
byte[] byteArray = myFile.getBytes("UTF-8");//Better to specify encoding
Blob blobData = null;
blobData.setBytes(1, byteArray);
The string contains my pdf file like this
BufferedReader input = null;
input = new BufferedReader(
new InputStreamReader(openFileInput(myFile)));
String line;
StringBuffer buffer = new StringBuffer();
while ((line = input.readLine()) != null) {
buffer.append(line + "\n");
}
String text = buffer.toString();
byte[] byteArray = text.getBytes("UTF-8");
Blob blobData = null;
blobData.setBytes(1, byteArray);
In my PHP-File I retrieve the blob like this
$pdf=$_GET['pdf']
$statement = $conn->prepare("INSERT INTO kunden(kunden_plz, kunden_nachname, kunden_vorname, kunden_adresse, kunden_ort, kunden_email, kunden_pdf) VALUES (?,?,?,?,?,?,?)");
$statement->bind_param("sssssss", $postleitzahl, $firstname,$lastname,$citytext,$address,$e_mail,$pdf );
$statement->execute();
My database is not getting the params
The line myFile.getBytes("UTF-8") doesn't read the file content, but only encodes the file path into byte[].
Check this resource to learn about file IO.

How to Decide InputStream Encoding?

My objective is to download an xml feed into an InputStream, then convert it to a String so that if may be used with XmlPullParser.
I convert the InputStream into a String like this:
InputStream input_stream = connection.getInputStream();
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(input_stream,"UTF-8"));
while ((line = br.readLine()) != null) {
sb.append(line);
}
Here's the problem, some XML feeds define specific encoding. Take this one for example:
http://voxinox.ch/podcasts/valdo/feed.xml
If I use a default of "UTF-8" encoding some characters from the feed look like a black rhombus shape with a question mark in it. If I use the encoding specified in the xml header it works (iso-8859-1), not a surprise.
The thing is how do I decide what encoding to use before I start reading the input stream which contains encoding specifications? Is there a better way of doing this?
Example how i get encoding from XML inputstream
FileInputStream finput = new FileInputStream(myFile);
String encoding = getInputEncoding(finput);
Log.d("Encoding: ", "> " + encoding);
public String getInputEncoding(FileInputStream finput){
String encoding = "";
if(finput!=null){
try{
BufferedReader myReader = new BufferedReader(new InputStreamReader(finput));
String getline = "";
getline = myReader.readLine();
myReader.close();
Log.d("Line: ", "> " + getline);
String[] separated = getline.split("encoding=\"");
String encoding1 = separated[1];
String[] separated2 = encoding1.split("\"");
encoding = separated2[0];
} catch (Exception e) {
}
}
return encoding;
}

Reading InputStream as UTF-8

I'm trying to read from a text/plain file over the internet, line-by-line. The code I have right now is:
URL url = new URL("http://kuehldesign.net/test.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
LinkedList<String> lines = new LinkedList();
String readLine;
while ((readLine = in.readLine()) != null) {
lines.add(readLine);
}
for (String line : lines) {
out.println("> " + line);
}
The file, test.txt, contains ¡Hélló!, which I am using in order to test the encoding.
When I review the OutputStream (out), I see it as > ¬°H√©ll√≥!. I don't believe this is a problem with the OutputStream since I can do out.println("é"); without problems.
Any ideas for reading form the InputStream as UTF-8? Thanks!
Solved my own problem. This line:
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
needs to be:
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
or since Java 7:
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8));
String file = "";
try {
InputStream is = new FileInputStream(filename);
String UTF8 = "utf8";
int BUFFER_SIZE = 8192;
BufferedReader br = new BufferedReader(new InputStreamReader(is,
UTF8), BUFFER_SIZE);
String str;
while ((str = br.readLine()) != null) {
file += str;
}
} catch (Exception e) {
}
Try this,.. :-)
I ran into the same problem every time it finds a special character marks it as ��. to solve this, I tried using the encoding: ISO-8859-1
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("txtPath"),"ISO-8859-1"));
while ((line = br.readLine()) != null) {
}
I hope this can help anyone who sees this post.
If you use the constructor InputStreamReader(InputStream in, Charset cs), bad characters are silently replaced. To change this behaviour, use a CharsetDecoder :
public static Reader newReader(Inputstream is) {
new InputStreamReader(is,
StandardCharsets.UTF_8.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT)
);
}
Then catch java.nio.charset.CharacterCodingException.

Categories