I want to convert Properties object to byte[], however i can do with the following piece of code but
private byte[] getBytes(Properties properties){
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter=new PrintWriter(stringWriter);
properties.list(printWriter);
String fileContent = stringWriter.getBuffer().toString();
byte[] bytes = fileContent.getBytes();
try{
stringWriter.close();
printWriter.close();
}catch (IOException e){
log.error("unable to close resource stringWriter" + e.getStackTrace());
}
return bytes;
}
but properties.list(printWriter), will print the string "--listing properties--" string to the console. Need help in finding the best way to do it.
I used a ByteArrayOutputStream to convert a Properties object. Your function could be modified to be the following -
private byte[] getBytes(Properties properties){
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try {
props.store(byteArrayOutputStream, "");
} catch (IOException e) {
log.error("An error occurred while storing properties to a byte array: " + e.getStackTrace());
}
return byteArrayOutputStream.toByteArray();
}
Properties file contains plain text, so to store a byte array you need to encode bytes to plain text. The best way is to use Base64 encodec.
String Base64.econdeToString(byte[])
And to retrieve bytes:
byte[] Base64.decode(String)
Related
Read some excel using poi failed, encountered such an error
Caused by: org.xml.sax.SAXParseException; systemId: file://; lineNumber: 105; columnNumber: 147342; An invalid XML character (Unicode: 0xffff) was found in the element content of the document.
at java.xml/com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:204)
at java.xml/com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.fatalError(ErrorHandlerWrapper.java:178)
at java.xml/com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:400)
From xl/sharedStrings.xml, there exist <ffff> cause this problem.
How could read it successfully and just ignore these invalid characters? e.g.
aaa <ffff> bbb ==> aaa bbb
Those invalid characters should not be in the XML and Excel itself will not put them into there. So someone probably had done something wrong while creating that file using something else than Excel. That error should be avoided rather than trying to ignore the symptoms.
But I know how it feels to be depemdent on others work which will be done in far future, if even. So one needs improvising. But that is in this case only possible using ugly low level methods. Because the XML is invalid, parsing XML is not possible. So only String replacing will be possible.
In APACHE POI EXCEL XmlException: is an invalid XML character, is there any way to preprocess the excel file? I had schown this already. In that case to replace UTF-16-surrogate-pair numeric character references which also are invalid in XML.
In following I will show a code which is more flexible to add multiple other repairing actions to /xl/sharedStrings.xml if necessary.
The principle is using OPCPackage, which is the *.xlsx ZIP package, to get out the /xl/sharedStrings.xml as text string. Then do the needed replacings and put the repaired /xl/sharedStrings.xml back into the OPCPackage. Then do creating the XSSFWorkbook from that repaired OPCPackage instead of from the corrupt file.
import java.io.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.openxml4j.opc.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
class RepairSharedStringsTable {
static String removeInvalidXmlCharacters(String string) {
String xml10pattern = "[^"
+ "\u0009\r\n"
+ "\u0020-\uD7FF"
+ "\uE000-\uFFFD"
+ "\ud800\udc00-\udbff\udfff"
+ "]";
string = string.replaceAll(xml10pattern, "");
return string;
}
static void repairSharedStringsTable(OPCPackage opcPackage) {
for (PackagePart packagePart : opcPackage.getPartsByName(Pattern.compile("/xl/sharedStrings.xml"))) {
String sharedStrings = "";
try (BufferedInputStream inputStream = new BufferedInputStream(packagePart.getInputStream());
ByteArrayOutputStream sharedStringsBytes = new ByteArrayOutputStream() ) {
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
sharedStringsBytes.write(buffer, 0, length);
}
sharedStrings = sharedStringsBytes.toString("UTF-8");
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println(sharedStrings);
//sharedStrings = replaceUTF16SurrogatePairs(sharedStrings);
sharedStrings = removeInvalidXmlCharacters(sharedStrings);
//sharedStrings = doSomethingElse(sharedStrings);
System.out.println(sharedStrings);
try (BufferedOutputStream outputStream = new BufferedOutputStream(packagePart.getOutputStream()) ) {
outputStream.write(sharedStrings.getBytes("UTF-8"));
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public static void main(String[] args) throws Exception {
try (XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream("./Excel.xlsx"))) {
System.out.println("success");
} catch (Exception ex) {
System.out.println("failed");
ex.printStackTrace();
}
OPCPackage opcPackage = OPCPackage.open(new FileInputStream("./Excel.xlsx"));
repairSharedStringsTable(opcPackage);
opcPackage.flush();
try (XSSFWorkbook workbook = new XSSFWorkbook(opcPackage);
FileOutputStream out = new FileOutputStream("./ExcelRepaired.xlsx");) {
workbook.write(out);
System.out.println("success");
} catch (Exception ex) {
System.out.println("failed");
ex.printStackTrace();
}
}
}
In my case below files all have invalid characters
xl/sharedStrings.xml
xl/worksheets/sheet1.xml
xl/worksheets/sheet8.xml
All these xml should be processed
opcPackage.getPartsByName(Pattern.compile("(/xl/sharedStrings.xml)|(/xl/worksheets/.+\\.xml)"))
I have been trying to make a string validator but some characters in the input have some swedish characters which I haven't been able to parse. I have been going mad about this. Tried everything I found on the internet. Can anybody please help me out?
This is the logic for reading the file. I have been trying to parse it.
I haven't been able to specifically parse this word: leverantör. It's parsed as leverant�r.
public String processFile(MultipartFile file) throws IOException, FormatNotFoundException {
// TODO Auto-generated method stub
BufferedReader r = new BufferedReader(new InputStreamReader(file.getInputStream()));
String output;
while((output = r.readLine())!=null ) {
logger.debug(output);
InputStream is= new ByteArrayInputStream(output.getBytes(StandardCharsets.UTF_8));
StringBuilder textBuilder = new StringBuilder();
try (
Reader reader = new BufferedReader(new InputStreamReader
(is, Charset.forName(StandardCharsets.UTF_8.name())))) {
int c = 0;
while ((c = reader.read()) != -1) {
textBuilder.append((char) c);
}
}
logger.debug(textBuilder.toString());
System.out.println(textBuilder.toString());
}
return "File read.";
}
I have developed a windows application to scan images.After the image is scanned i want to save it directly to the database not in local machine...The code which i have used is as follows
try
{
String str = string.Empty;
WIA.CommonDialogClass scanner;
ImageFile imageObject;
scanner = new CommonDialogClass();
imageObject = scanner.ShowAcquireImage
(WiaDeviceType.ScannerDeviceType,
WiaImageIntent.ColorIntent,
WiaImageBias.MinimizeSize,
ImageFormat.Jpeg.Guid.ToString("B"),
false,
true,
true);
str = DateTime.Now.ToString();
str = str.Replace("/", "");
str = str.Replace(":", "");
Directory.CreateDirectory("D:\\scanned1");
// MessageBox.Show(string.Format("File Extension = {0}\n
//\nFormat = {1}", imageObject.FileExtension, imageObject.FormatID));
imageObject.SaveFile(#"D:\scanned1\lel" + str + ".jpg");
MessageBox.Show("Scanning Done");
}
catch (Exception ex)
{
MessageBox.Show("Please check if the scanner is connected properly.");
}
Instead of saving it to D drive i want to save it to database.....How can i do it?Plz reply...
I've got no idea what "ImageFile" is really, but there should be a way to transform it into the byte array (byte[]). Afterwards you would need to insert that array to varbinary field in your sql.
something like this:
using(SqlCommand cmd = new SqlCommand("INSERT INTO MyTable (myvarbinarycolumn) VALUES (#myvarbinaryvalue)", conn))
{
cmd.Parameters.Add("#myvarbinaryvalue", SqlDbType.VarBinary, myarray.length).Value = myarray;
cmd.ExecuteNonQuery();
}
ofc sqlcommand should be opened and valid.
myarray is of type byte[]
I have a problem.
I must get a md5 hash of string in Java ME.
I have that code
public static String md5(String input) throws UnsupportedEncodingException{
String res = "";
try {
MessageDigest algorithm = MessageDigest.getInstance("MD5");
algorithm.reset();
algorithm.update(input.getBytes("UTF-8"));
byte[] md5 = algorithm.digest();
return md5.toString();
}
catch (NoSuchAlgorithmException ex) {}
return res;
}
But MessageDigest.update() and MessageDigest.digest() accept only 3 arguments.
Any ideas?
The two other arguments are offset and len, which you can set to 0 and the length of the byte buffer respectively.
I used this question
How do I convert an InputStream to a String in Java?
to convert an InputStream to a String with this code:
public static String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
My inputstream comes from an HttpURLConnection InputStream, and when I do my conversion to String, the inputstream changes and I cannot longer use it. This is the error that I get:
Premature end of file.' SOAP
What can I do to keep my inputstream, when I convert it to string with the proper information?.
Speciffically this is the information that changes:
inCache = true (before false)
keepAliveConnections = 4 (before 5)
keepingAlive = false (before true)
poster = null (before it was PosterOutputStream object with values)
Thank you.
If you pass your input stream into scanner or read its data in any other way. you actually consuming its data and there will be no available data in that stream anymore.
you may need to create a new input stream with same data and use it instead of the original one. for example:
ByteArrayOutputStream into = new ByteArrayOutputStream();
byte[] buf = new byte[4096];
// inputStream is your original stream.
for (int n; 0 < (n = inputStream.read(buf));) {
into.write(buf, 0, n);
}
into.close();
byte[] data = into.toByteArray();
//This is your data in string format.
String stringData = new String(data, "UTF-8"); // Or whatever encoding
//This is the new stream that you can pass it to other code and use its data.
ByteArrayInputStream newStream = new ByteArrayInputStream(data);
The scanner reads till the end of the stream and closes it. So it will not be available further. Use PushbackInputStream as a wrapper to your input stream and use the unread() method.
Try to Use Apache Utilities.
In my preset project, I have done the same thing
InputStream xml = connection.getInputStream();
String responseData = IOUtils.toString(xml);
You can get IOUtils from Apache [import org.apache.commons.io.IOUtils]