public static void writeIntoFile() {
FileOutputStream fileOutputStream = null;
ObjectOutputStream objectOutputStream = null;
try {
fileOutputStream = new FileOutputStream("Employee.txt");
objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(list1);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fileOutputStream == null) {
System.out.println("file is not created");
}
if (objectOutputStream == null) {
System.out.println("cant able to write");
}
}
}
I want to using this function to writing in a file. it writes successfully but it display data in bytecode. how can I save it into string format?
Use a FileWriter wrapped inside a BufferedWriter to write character data to a File.
ObjectOutputStream is used for serialization and results in a binary encoded file. Its only useful if you only want to load the file through your program and do not wish to read its contents elsewhere like in an external editor.
You also need to iterate through your List and save the requisite properties of your underlying Object in a format you wish to parse your File later on in. For example, as CSV (comma separated values) every Employee object and its properties would be persisted as one single line in the output file.
BufferedWriter br = new BufferedWriter(new FileWriter("Employee.csv"));
for (Employee employee : list) {
br.write(employee.getFName() + ", " + employee.getLName());
br.newLine();
}
br.close();
in the function writeIntoFile is write a Serialization Object into file
you should use the object's toString() to write a String into file
you can change bytecode into string using one simple way.
pass the bytecode into string constructor
like this:
new String(bytecode object);
and then write string object into file.
Related
I am trying to write data to a binary file and am having difficulty. When I run this method I don't get any output to the file. Also when it comes to writing my "Date" object, I can't seem to find a write method that takes it as a parameter. The object consists of an int month, day, and year. How can I write it into a binary file properly?
Also, does "File" work for binary as well? I have only previously used it for regular .txt files and I'm not sure if it can be used the same way in this situation. Thanks!
Here is my write method:
private void writeBinary(){
//String fileName = getUserInput();
String fileTest = "BinaryMonster.bin";
File file = new File(fileTest);
DataOutputStream out;
try{
out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file, true)));
if(!(file.exists())){
file.createNewFile();
System.out.println("New file created...");
}
for(int i = 0; i < monsterAttacks.size(); i++){
out.writeInt(monsterAttacks.get(i).getID());
out.write(monsterAttacks.get(i).getDate()); //getting error
out.writeUTF(monsterAttacks.get(i).getName() + monsterAttacks.get(i).getLocation() + monsterAttacks.get(i).getReporter());
}
} catch(IOException e) {
e.printStackTrace();
}
}
It is giving error because you are writing whole object of date into the file using DataOutputStream, which don't allow you to do that.
Write it in the form of String into the file. It will be better.
out.writeUTF(monsterAttacks.get(i).getDate().toString());
But if you want to save the whole object into the file, then you need to use ObjectOutputStream which write whole serialized objects into the file.
And it is better approach to flush and close the file.
out.flush();
out.close();
I am creating a listview with json data.When user is offline I want to show the data in listview. I have stored the json data in android sdcard. And I retrive the data when user is offline and showed it in listview. The problem is, when I read the file from directory it's show's me black diamond with a question mark and stores it in array list. this type of "����t��*" my question is how to remove this type of string from Arraylist. Someone please help
Save the Data:
public void saveMyData()
{
try {
ObjectOutput out = new ObjectOutputStream(new FileOutputStream(new File(getFilesDir(),"")+"cachefile.txt"));
out.writeObject(al.toString());
Toast.makeText(getApplicationContext(), "Data Saved..",Toast.LENGTH_LONG).show();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
This is my retrieving code.
String fileContent = "";
try {
String currentLine;
BufferedReader bufferedReader;
FileInputStream fileInputStream = new FileInputStream(getFilesDir()+"cachefile.txt");
bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream,"UTF-8"));
while ((currentLine = bufferedReader.readLine()) != null) {
fileContent += currentLine + '\n';
}
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
Log.d("FAILED","THOS IS NULL");
fileContent = null;
}
Log.d("SUCESS","SUCESS BUDDYY"+fileContent);
Broadly speaking, the issue is that you're using an ObjectOutputStream to write your data to the file, but a BufferedReader to read it back in. The ObjectOutputStream is specifically designed to allow objects and native data types to be written to a stream in a way they can be read back in via an ObjectInputStream to reconstitute the objects in the same way. This encoding is not meant to be human readable and usually contains extra characters as field separators.
I don't know what al is, but since you're calling toString() before you write it, I can assume that you want actual strings in a file you can read. To do this, you probably want to use a PrintStream and the PrintStream.println() method instead of the ObjectOutputStream.
I have this piece of code, just to try to write it to a file. But when I compile it, it doesn't display any errors, but text in my file is unreadable, some Unicode codes etc... I use eclipse IDE. What could be the reason for this?
public static void main(String[] args) {
String s = "Hello world!";
int i = 143141141;
try
{
//create new file with an ObjectOutputStream
FileOutputStream out = new FileOutputStream("test.txt");
ObjectOutputStream oout = new ObjectOutputStream(out);
//write something in a file
oout.writeObject(s);
oout.writeObject(i);
//close the stream
oout.close();
//create an ObjectInputStream for the file we created before
ObjectInputStream ois = new ObjectInputStream(
new FileInputStream("test.txt"));
//read and print what we wrote before
System.out.println("" + (String) ois.readObject());
System.out.println("" + ois.readObject());
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
Since you are using ObjectOutputStream and ObjectInputStream , it will write in Object code , which is not readable , and as well when u read from file , it will come up as an Object so again as an Object ,
Use BufferedReader or Writer to write String into file , which can be read
FileReader f=new FileReader(new File("test.txt"));
BufferedReader f1=new BufferedReader(f)
;
With an ObjectOutputStream, you're using Serialization to write your objects to a file. Serialization is using an encoding system, and you use correctly an ObjectInputStream in your program to decode these objects. But you won't be able to read the information in the file created by the Serialization process.
You should use PrintWriter to write text files, ObjectOutputStream writes binary data.
Java ObjectOuputStream writes objects in a binary non human readable format which can be read only with ObjectInputStream.
Your code is working fine for me. If I understand it correctly when look at the contents of file by opening it in editor (say notepad or eclipse) you see characters stored as binary content in it. As you are using ObjectInputStream and ObjectOutputStream the behavior is correct.
You are not writing values of your String and Integer objects but their object representations in binary format. That is called object-serialization. That is some how encoded to represent all the information associate with the object not only its value That is only displayed when decoded in the same way as we encoded them. So, normal text editor cannot display the information as you expected.
If you want to save the string representation only, use the classes such as PrintWriter.
I tried your code. It's working perfectly for me. See the attached image.
Try cleaning your workspace. If it doesn't work, try creating a new Java project and copy the same code posted here and try. It should work.
You're making the folly of writing the output string through an ObjectOutputStream which serializes the String and Integer objects in your code and saves the Object state along with the value of the object. This is the reason why you see encoded text when you open the file. The following excerpt sums up the values which are stored when an Object is serialized:
The default serialization mechanism for an object writes the class of the object, the class signature, and the values of all non-transient and non-static fields. References to other objects (except in transient or static fields) cause those objects to be written also. Multiple references to a single object are encoded using a reference sharing mechanism so that graphs of objects can be restored to the same shape as when the original was written.(ObjectOutputStream)
The writeObject method is responsible for writing the state of the object for its particular class so that the corresponding readObject method can restore it.
Primitive data, excluding serializable fields and externalizable data, is written to the ObjectOutputStream in block-data records. A block data record is composed of a header and data. The block data header consists of a marker and the number of bytes to follow the header. (ObjectOutputStream javadoc)
The possible problem with your code is you are not flushing the output data. So that it might not get written to the output file.
Try the below code.
public static void main(String[] args) {
String s = "Hello world!";
int i = 143141141;
try
{
//create new file with an ObjectOutputStream
FileOutputStream out = new FileOutputStream("test.txt");
ObjectOutputStream oout = new ObjectOutputStream(out);
//write something in a file
oout.writeObject(s);
oout.flush();
oout.writeObject(i);
oout.flush();
//close the stream
out.close();
oout.close();
//create an ObjectInputStream for the file we created before
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test.txt"));
//read and print what we wrote before
System.out.println("" + (String) ois.readObject());
System.out.println("" + ois.readObject());
ois.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
And also if you want to read your written objects into the file then you can't because they are written as serialized objects. For textual operation with files you can consider BufferedReader or PrintWriter. see the following code.
public class WriteToFileExample {
public static void main(String[] args) {
try {
String content = "This is the content to write into file";
File file = new File("c:\\desktop\\filename.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}
After this you can open your text file and can see the written content in the human readable form and it is good practice to not to give "txt" formats when you are writing objects to the file. It's misleading.
Hope this helps.
I'm having memory problem as working with very large dataset and getting memory leaks with char[] and Strings, don't know why! So I am thinking of writing some processed data in a file and not store in memory. So, I want to write texts from an arrayList in a file using a loop. First the program will check if the specific file already exist in the current working directory and if not then create a file with the specific name and start writing texts from the arrayList line by line using a loop; and if the file is already exist then open the file and append the 1st array value after the last line(in a new line) of the file and start writing other array values in a loop line by line.
Can any body suggest me how can I do this in Java? I'm not that good in Java so please provide some sample code if possible.
Thanks!
I'm not sure what parts of the process you are unsure of, so I'll start at the beginning.
The Serializable interface lets you write an object to a file. Any object that implemsents Serializable can be passed to an ObjectOutputStream and written to a file.
ObjectOutputStream accepts a FileOutputStream as argument, which can append to a file.
ObjectOutputstream outputStream = new ObjectOutputStream(new FileOutputStream("filename", true));
outputStream.writeObject(anObject);
There is some exception handling to take care of, but these are the basics. Note that anObject should implement Serializable.
Reading the file is very similar, except it uses the Input version of the classes I mentioned.
Try this
ArrayList<String> StringarrayList = new ArrayList<String>();
FileWriter writer = new FileWriter("output.txt", true);
for(String str: StringarrayList ) {
writer.write(str + "\n");
}
writer.close();
// in main
List<String> SarrayList = new ArrayList<String>();
.....
fill it with content
enter content to SarrayList here.....
write to file
appendToFile (SarrayList);
.....
public void appendToFile (List<String> SarrayList) {
BufferedWriter bw = null;
boolean myappend = true;
try {
bw = new BufferedWriter(new FileWriter("myContent.txt", myappend));
for(String line: SarrayList ) {
bw.write(line);
bw.newLine();
}
bw.flush();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
if (bw != null) try {
bw.close();
} catch (IOException ioe2) {
// ignore it or write notice
}
}
}
I have file contents in a java string variable, which I want to convert it into a File object is that possible?
public void setCfgfile(File cfgfile)
{
this.cfgfile = cfgfile
}
public void setCfgfile(String cfgfile)
{
println "ok overloaded function"
this.cfgfile = new File(getStreamFromString(cfgfile))
}
private def getStreamFromString(String str)
{
// convert String into InputStream
InputStream is = new ByteArrayInputStream(str.getBytes())
is
}
As this is Groovy, you can simplify the other two answers with:
File writeToFile( String filename, String content ) {
new File( filename ).with { f ->
f.withWriter( 'UTF-8' ) { w ->
w.write( content )
}
f
}
}
Which will return a file handle to the file it just wrote content into
Try using the apache commons io lib
org.apache.commons.io.FileUtils.writeStringToFile(File file, String data)
You can always create a File object from a String using the File(String) constructor. Note that the File object represents only an abstract path name; not a file on disk.
If you are trying to create an actual file on disk that contains the text held by the string there are several classes that you can use, for example:
try {
Writer f = new FileWriter(nameOfFile);
f.write(stringToWrite);
f.close();
} catch (IOException e) {
// unable to write file, maybe the disk is full?
// you should log the exception but printStackTrace is better than nothing
e.printStackTrace();
}
FileWriter will use the platform default encoding when converting the characters of the string to bytes that can be written on disk. If this is a problem you can use a different encoding by wrapping FileOutputStream inside an OutputStreamWriter. For example:
String encoding = "UTF-8";
Writer f = new OutputStreamWriter(new FileOutputStream(nameOfFile), encoding);
To write a String to a file, you usually should use a BufferedWriter:
private writeToFile(String content) {
BufferedWriter bw;
try {
bw = new BufferedWriter(new FileWriter(this.cfgfile));
bw.write(content);
}
catch(IOException e) {
// Handle the exception
}
finally {
if(bw != null) {
bw.close();
}
}
}
Besides, the new File(filename) simply instanciates a new File object with the name filename (it does not actually create the file on your disk). Therefore, you statement:
this.cfgfile = new File(getStreamFromString(cfgfile))
will simple instanciate a new File with the name the String returned by the this.cfgfile = new File(getStreamFromString method.