I am getting this error when converting inputStream into ObjectInputStream.
Please help me regarding this.
My Code:
InputStream isSchema = Thread.currentThread()
.getContextClassLoader().getResourceAsStream("schema.xsd");
ObjectInputStream inputStream = new ObjectInputStream(isSchema);
Exception:
java.io.StreamCorruptedException: invalid stream header: 3C787364
3C787364 in hexadecimal is <xsd .
schema.xsd is not a file of serialized objects previously written using an ObjectOutputStream. You must use InputStreamReader.
Just an example
InputStream inputStream = new FileInputStream("c:\\data\\input.txt");
Reader reader = new InputStreamReader(inputStream);
int data = reader.read();
while(data != -1){
char theChar = (char) data;
data = reader.read();
}
reader.close();
Related
Text I am reading from a XML, which is suppose to be a string with base64 encoded and Gzip compressed. I am following the below steps:
string text = childNodes.Item(i).InnerText.Trim();
byte[] compressed = Convert.FromBase64String(text);
byte[] compressed = Convert.FromBase64String(text);
using (var uncompressed = new MemoryStream())
using (var inStream = new MemoryStream(compressed))
using (var outStream = new GZipStream(inStream, CompressionMode.Decompress))
{
outStream.CopyTo(uncompressed);
var reader = new StreamReader(uncompressed);
uncompressed.Position = 0;
string myStr = reader.ReadToEnd();
Console.WriteLine(myStr);
}
I am getting myStr value as something like :
�\b\0\0\0\0\0\0Ľk��ƒ �Y��ؘX{���z:�n�,ɏ�ek��xϞ�`�\0؍�|\t ��_3�\n(\0$�s.Cb�\0*3++��|
͛ �-7�6�fW\r\t�\b���W\"�\n�ə��L&���Ez�-����E��\t�%���/���O��Q����
i�����]�T�b�<_�dŦ�W۫���ܭn^[X�ϕ��{�"
I am expecting adecoded string. Any hint on this is much appreciated.
Thanks in Advance. :)
i am having an issue when trying to read saved List from binary file back to a List.
the file is encrypted, without encryption i had no problem.
writing method:
private void WriteEncodedFile(FileStream fileStream, MemoryStream memoryStream)
{
StreamReader sr = new StreamReader(memoryStream);
BinaryWriter bw = new BinaryWriter(fileStream);
memoryStream.Seek(0, SeekOrigin.Begin);
string data = sr.ReadToEnd();
var bytes = Encoding.UTF8.GetBytes(data);
for (int i = 0; i < bytes.Length; i++) bytes[i] ^= 0x5a;
bw.Write(Convert.ToBase64String(bytes));
bw.Close();
fileStream.Close();
}
Reading method:
private void ReadEncodedFile(FileStream fileStream, MemoryStream memoryStream)
{
BinaryReader br = new BinaryReader(fileStream);
StreamWriter sw = new StreamWriter(memoryStream);
fileStream.Seek(0, SeekOrigin.Begin);
memoryStream.Seek(0, SeekOrigin.Begin);
string base64 = br.ReadString();
byte[] bytes = Convert.FromBase64String(base64);
for (int i = 0; i < bytes.Length; i++) bytes[i] ^= 0x5a;
string decodedData = Encoding.UTF8.GetString(bytes);
sw.Write(decodedData);
}
when reading the content i can see it in the "decodedData".
however the StreamWriter seems not to write it into the MemoryStream.
any idea?
thanks.
I think you are simply not flushing/closing the stream before checking.
sw.Flush();
or
sw.Close();
if done
and
fileStream.Close(); for good practice too
Edit:
Considering the comment, you need to seek to start of memory stream again before deserialising
i.e. memoryStream.Seek(0, SeekOrigin.Begin); where-ever you do it
I am trying to zip a 30Mb excel file.
Wrapping th fileinputstream and fileoutputstream reduced some of the memory consumption.
Please suggest if you have a better option than this approach.
Do you think, flushing the ZipOutputStream after zos.write() inside while loop will be of any advantage?
Following is the code which i use.
public void zipBigFile()
throws IOException, ParseException {
String outFileName= "D:/Out/Big.zip";
File file = new File(outFileName);
FileOutputStream out = new FileOutputStream(file);
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(out));
byte[] buffer = new byte[1024 * 8];
String inFileName = "D:/In/Big_File.xlsx";
FileInputStream fis = new FileInputStream(inFileName);
BufferedInputStream bis = new BufferedInputStream(fis);
ZipEntry zipEntry = new ZipEntry("Big_File_Zipped.xlsx");
zos.putNextEntry(zipEntry);
int length;
while ((length = bis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
zos.closeEntry();
fis.close();
fis = null;
buffer = null;
zos.flush();
zos.close();
out.close();
out = null;
zos = null;
}
please help me
java server throws : java.lang.IllegalStateException: Cannot call sendError() after the response has been committed
I rechecked many times and googled alot but i cant find what's the problem
here's my code
DataOutputStream stream = null;
BufferedInputStream buf = null;
try {
response = ServletActionContext.getResponse();
response.setHeader(Constants.AU_TRST_X_RESULT_CD, "0"); // x-resultCd = 0 is OK
// add RSP_KEY_CODE to header
response.setHeader(Constants.RSP_KEY_CODE, Constants.RSP_SUCCCESS + "");
response.setContentType("application/csv");
//------------ write csv file to body ----------
// get response's outputStream
stream = new DataOutputStream(response.getOutputStream());
// fix file csv
File csvFixFile = new File("E:\\a.xls");
// buffer to read csv File
File csvResponse = new File(csvFixFile.getPath());
// file Input to read csv File
FileInputStream inputStream = new FileInputStream(csvResponse);
buf = new BufferedInputStream(inputStream);
int readBytes = 0;
while ((readBytes = buf.read()) != -1) {
stream.write(readBytes);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (null != buf)
try {buf.close();} catch (Exception e2) {e2.printStackTrace();}
if (null != stream)
try {stream.close();} catch (Exception e2) {e2.printStackTrace();}
}
.It looks okay but it didnt work properly and perhaps the problem is in the while loop
please point it out for me.....
You can use IOUtils from apache commons-io to copy input stream into output stream (it also uses buffer, so you don't need to):
ServletOutputStream outStream = response.getOutputStream();
IOUtils.copy(inputStream, outStream);
IOUtils javadoc
I am working on implementing a SAMLSLO through HTTP-REDIRECT binding mechanism. Using deflate-inflate tools gives me a DataFormatException with incorrect header check.
I tried this as a stand-alone. Though I did not get DataFormatException here I observed the whole message is not being returned.
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
public class InflateDeflate {
public static void main(String[] args) {
String source = "This is the SAML String";
String outcome=null;
byte[] bytesource = null;
try {
bytesource = source.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
int byteLength = bytesource.length;
Deflater compresser = new Deflater();
compresser.setInput(bytesource);
compresser.finish();
byte[] output = new byte[byteLength];
int compressedDataLength = compresser.deflate(output);
outcome = new String(output);
String trimmedoutcome = outcome.trim();
//String trimmedoutcome = outcome; // behaves the same way as trimmed;
// Now try to inflate it
Inflater decompresser = new Inflater();
decompresser.setInput(trimmedoutcome.getBytes());
byte[] result = new byte[4096];
int resultLength = 0;
try {
resultLength = decompresser.inflate(result);
} catch (DataFormatException e) {
e.printStackTrace();
}
decompresser.end();
System.out.println("result length ["+resultLength+"]");
String outputString = null;
outputString = new String(result, 0, resultLength);
String returndoc = outputString;
System.out.println(returndoc);
}
}
Surprisingly I get the result as [22] bytes, the original is [23] bytes and the 'g' is missing after inflating.
Am I doing something fundamentally wrong here?
Java's String is a CharacterSequence (a character is 2 bytes). Using new String(byte[]) may not correctly convert your byte[] to a String representation. At least you should specify a character encoding new String(byte[], "UTF-8") to prevent invalid character conversions.
Here's an example of compressing and decompressing:
import java.util.zip.Deflater;
import java.util.zip.InflaterInputStream;
...
byte[] sourceData; // bytes to compress (reuse byte[] for compressed data)
String filename; // where to write
{
// compress the data
Deflater deflater = new Deflater(Deflater.DEFAULT_COMPRESSION);
deflater.setInput(sourceData);
deflater.finish();
int compressedSize = deflater.deflate(data, 0, sourceData.length, Deflater.FULL_FLUSH);
// write the data
OutputStream stream = new FileOutputStream(filename);
stream.write(data, 0, compressedSize);
stream.close();
}
{
byte[] uncompressedData = new byte[1024]; // where to store the data
// read the data
InputStream stream = new InflaterInputStream(new FileInputStream(filename));
// read data - note: may not read fully (or evenly), read from stream until len==0
int len, offset = 0;
while ((len = stream.read(uncompressedData , offset, uncompressedData .length-offset))>0) {
offset += len;
}
stream.close();
}