Comparing two ByteArrayOutputStreams in Java - java

I'm writing output to an excel file which is being written through ByteArrayOutputStream. I want to write test for comparing the expected ByteArrayOutputStream(whether the excel cell contains the data as I required) with the output ByteArrayOutputStream .Is there a way to compare two ByteArrayOutputStreams in Java ? Also how should I set my expected outputStream ?

You can compare their content by doing something like this:
Arrays.equals(byteArrayOutputStream1.toByteArray(), byteArrayOutputStream2.toByteArray());
You can set its content like any other OutputStream thanks to the write methods if the content is big, but If your expected value is small, the better approach will be to put the content into a String variable then do the next test instead of the previous one:
Arrays.equals(expectedContent.getBytes(myCharset), byteArrayOutputStream2.toByteArray());

Related

write to file - which way is cleaner?

I am using java.io.PrintWriter to write some text to a text file.
I was wondering if it was better to build in a variable all what I need to write and give only once
PrintWriter out = new PrintWriter(outputfile);
out.printf("%s", myvariablewithalltext);
or if I can call n times PrintWriter to write block of text in a for loop.
It works in either way and there is no much more code, I was just wondering which is better.
In most cases it's better to write in stream. The main reason is that your variable might take too much memory, but stream will automatically flush it's content. Writing text into the variable is essentially manual buffering. And better way to do it is to use appropriate buffering stream/writer. In you case you can just use java.io.BufferedWriter. Like so
BufferedWriter out = new BufferedWriter(new PrintWriter("file.txt"));
or, if you prefer PrintWriter interface, you can do this
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("file.txt")));
Assuming you are open for other suggestions (not just the two you mentioned in question).
If all you want is a clean way of writing text to a file, which of course has multiple solutions, here are few ways:
Using PrintWriter.
example:
String contentToWrite = "This is some random Text";
PrintWriter writerToFile = new PrintWriter("TheOutputFile.txt");
writerToFile.print(contentToWrite);
writerToFile.close();
Using FileOutputStream
example:
String contentToWrite = "This is some random Text";
FileOutputSream fileOPS = new FileOutputStream("TheOutputFile.txt");
fileOPS.write(contentToWrite.getBytes());
fileOPS.close();
Using Files
Using FileWriter along with BufferWriter
Using FileUtils by apache.commons.io
Using Files by guava
Some approaches here just take the content (no parsing or conversion required i.e in string format) and write that to a file. [ no parsing/conversion -> less code -> cleaner code ]. ;)
Some do not require you to make nesting of objects. [ less objects -> less code -> cleaner code ]. ;)
Of course usage depends on your implementation. but I hope this will help you in making decision what would best suit your requirement.
Note: every class name I mentioned is a link to its reference document.
It is the latter. There is no good reason whatsoever to put the entire content into a variable, just to write it in a file.
If you have some additional use for that variable beyond writing to file, that might change things a little bit, but even then, there is, probably, a better way.
I think it depends on your content lenght.
If you have just some litle text, it's better to keep all in memory and write in one shot.
But if your content is very large or if some part take long time to computed, probably you should write piece by piece to avoid have huge data kept in memory.

how to ignore first two bytes hdfs writeUTF and writeChars?

I have written some data in hdfs, but i want that to be without the first two bytes that the writeUTF() method writes. I want to copy this first two byte free hdfs file to local file and do some analysis on it.
if (fs.exists(filenamePath)) {
// remove the file first
//fs.delete(filenamePath);
out = fs.append(filenamePath);
}
// create if file doesnt exists
else{
out = fs.create(filenamePath);
}
out.writeUTF(getFeaturesString(searchCriteriaList,fileNameData));
out.close();
The data written is as follows
0aEX Series ex4200-24f....
I want only
EX Series ex4200-24f
I write all the data to hdfs file and then I am copying the file into local to do some analysis. Is there an alternative method to accomplish this..
how to ignore first two bytes hdfs writeUTF() and writeChars()?
You've just answered your own question. Use writeChars().
writeUTF() is only useful when somebody is going to be calling readUTF() to read it. It uses a modified character set and a length-word that is only understood by readUTF().
There's no particular reason to use DataOutputStream here either. If the data is all text, use a BufferedWriter.

How to save an array or object to be used in other runs

I'm working with a sensor that taking data and giving it to me whenever I call on it. I want to collect 1 minute of data in an arraylist and then save it to a file or something so that I can analyze it at a different time.
So I have something like this:
ArrayList<DataObject> data = new ArrayList<DataObject>();
public void onUpdate(DataObject d) { //being called by my sensor every second
data.add(d);
}
I want to save the ArrayList data to a file to my computer so that I can later feed it into a different program and use it there.
How do I go about doing this?
If you want to save these as CSV files, they'll be easily exportable and importable, even to Excel (which may be of value for doing further work or passing on results).
Check out OpenCSV and in particular this entry in the FAQ relating to writing the data out.
e.g.
CSVWriter writer = new CSVWriter(new FileWriter("yourfile.csv"), ',');
// feed in your array (or convert your data to an array)
String[] entries = "first#second#third".split("#");
writer.writeNext(entries);
writer.close();
I think you should just output the values to a file with something as a delimiter between the values, then read the files into an array in a new program. To get the array into a file, loop through the array while appending each number to a file when looped through until you reach the end.
If the other program is also based on Java, you could leverage the Java Serializable inferface. Here is a tutorial, Java - Serialization.
it would be best to use ObjectOutputStream for the purpose, since the output of the sensor is a integer or double. using writeObject method method your task can be done.
see the link for a detailed reading:
http://docs.oracle.com/javase/7/docs/api/java/io/ObjectOutputStream.html

How to store data in text file in java

How to store data in text file in java that has various attributes like name, author etc that will be inputted by the user on CLI.
any Idea?
Thanks
It sounds like the Java class that will suit you best is a FileWriter. However, if you are writing a file with Key=Value lines, then the Properties class might end up being the better choice.
"[S]tore data in text file" sounds like you want a readable format. You can use comma-separated value (CSV) files.
You can write your own CSV serializer (search on SO for "how to write csv java") or use a solution like the Java CSV library.
Use DataOutputStream and DataInputStream. Using this class make it easier to read integer, float, double data and others without needing to interpret if the read data should be an integer or a float data.
something lyk dis
DataOutputStream dos = new DataOutputStream(fos);
//
// Below we write some data to the cities.dat.
// DataOutputStream class have various method that allow
// us to write primitive type data and string. There are
// method called writeInt(), writeFloat(), writeUTF(),
// etc.
//
dos.writeInt(cityIdA);
dos.writeUTF(cityNameA);
dos.writeInt(cityPopulationA);
dos.writeFloat(cityTempA);
dos.writeInt(cityIdB);
dos.writeUTF(cityNameB);
dos.writeInt(cityPopulationB);
dos.writeFloat(cityTempB);
dos.flush();
dos.close();

Magic number file checking

I'm attempting to read magic numbers/bytes to check the format of a file. Will reading a file byte by byte work in the same way on a Linux machine?
Edit: The following shows to get the magic bytes from a class file using an int. I'm trying to do the same for a variable number of bytes.
http://www.rgagnon.com/javadetails/java-0544.html
I'm not sure that I understand what you are trying to do, but it sounds like what you are trying to do isn't the same thing as what the code that you are linking to is doing.
The java class format is specified to start with a magic number, so that code can only be used to verify if a file might be a java class or not. You can't use the same logic and apply it to arbritraty file formats.
Edit: .. or do you only want to check for wav files?
Edit2: Everything in Java is in big endian, that means that you can use DataInputStream.readInt to read the first four bytes from the file, and then compare the returned int with 0x52494646 (RIFF as a big endian integer)

Categories

Resources