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();
Related
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.
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.
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
There are too many java.io classes, for some of them i really dont understand when we need them, for example:
ByteArrayInputStream, ByteArrayOutputStream
SequenceInputStream,
PushbackInputStream, PushbackReader
StringReader...
I mean some real-life usages
Can someone please explain...
I would say that your question is too wide.
However it is possible to give a very basic overview of java.io package. It contains interfaces and classes for data input and output operations, such as reading bytes from file. There are only few basic interfaces / classes:
DataInput / ObjectInput - readig Java primitives and objects
DataOutput / ObjectOutput - writing Java primitives and objects
InputStream - reading individual bytes
OutputStream - writing individial bytes
Reader - reading character data
Writer - writing character data
There are other useful interfaces (like Closeable), but these are less significant.
It is best if you read the JavaDoc of these classes. Some examples:
It is pretty obvious that you would use FileOutputStream to write something into a file.
Character data is represented by bytes (defined by character encoding), so you can wrap any output stream using OutputStreamWriter.
You have byte[] and want to read from it just like from InputStream? Use ByteArrayInputStream.
You want to be able to return read bytes back to the reader (usually only a single pass-through is supported)? Wrap your reader with PushbackReader.
You have some String and want to read from it just like from Reader? Use StringReader.
...
So if you need some specific stream/reader/writer, check java.io package, search the internet and ask a question on SO if needed.
Of course then there is java.nio package, which you should know about. But that is for a different topic.
I'm working on a chat room application for android. I read different tutorials; some of them use PrintWriter to send data and some of them use DataOutputStream. What is the difference between these two? Which one is better for a chat app?
From java docs
A DataOutputStream lets an application write primitive Java data types to an output stream in a portable way. An application can then use a data input stream to read the data back in.
PrintWriter Prints formatted representations of objects to a text-output stream. This class implements all of the print methods found in PrintStream. It does not contain methods for writing raw bytes, for which a program should use unencoded byte streams.
In one sentence the difference is:
OutputStreams are meant for binary data. Writers (including PrintWriter) are meant for text data
PrintWriter converts everything to Ascii format. For example:
PrintWriter pw = new PrintWriter(new File("./test.txt"));
for (Integer word: words) {
pw.println(word);
}
in this block of code, by calling pw.printin(word); no matter what the type of word is (which is integer here), program converts it to ASCII format and stores it. As a result, when we want to retrieve that stored data and read it again, program have to do another type changing from text to original format! -which is not good in term of time efficiency!
For instance, if that word is an integer, after storing that into a file (which is text now), program has to change its format from String to integer when it is going to retrieve that!
But, DataOutPutStream makes everything much easier since it stores the data into bytes by keeping data type. So, when we run bellow block, program stored integer as byte and when it want to retrieve that it does not need any change of type. It's stored as integer and retrieved as integer too. So, it is much faster!
DataOutputStream dos = new DataOutputStream(
new FileOutputStream(new File("test2.txt")));
for (Integer word: words) {
dos.writeUTF(word);
}
dos.close();
Both DataOutputStream and PrintWriter are two classes in java.io.
class DataOutputStream extends FilterOutputStream implements DataOutput {
}
Javadoc says
"A data output stream lets an application write primitive Java data types to an output stream in a portable way. An application can then use a data input stream to read the data back in."
public class PrintWriter extends Writer {
}
Prints formatted representations of objects to a text-output stream. This class implements all of the print methods found in PrintStream. It does not contain methods for writing raw bytes, for which a program should use unencoded byte streams.