My teacher said that in file server program ObjectInputStreamReader is compulsory to write. When I asked the reason then he said me it is comfortable for file server program. I am thinking that it is not necessary reason. Why InputStreamReader or other alternatives can not be used? what is the advantage of ObjectInputStreamReader over InputStreamReader.
Here code for client/server:
public class Client {
public static void main(String[] args) {
Socket s = null;
ObjectInputStream ois = null;
ObjectOutputStream oos = null;
Scanner sc = new Scanner(System.in);
String data = "";
try {
s = new Socket("localhost", 1234);
System.out.println("client is connectd");
ois = new ObjectInputStream(s.getInputStream());
String jai = (String) ois.readObject();
System.out.println("DATA from SERVER:" + jai);
oos = new ObjectOutputStream(s.getOutputStream());
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Enter file name:");
try {
String fil = (String) sc.next();
OutputStream pw = new FileOutputStream(fil + ".new");
oos.writeObject(fil);
data = (String) ois.readObject();
pw.write(data.getBytes());
} catch (Exception e) {
System.out.println(e.getMessage());
}
System.out.println("Content of file:" + data);
}
}
Can any one say what is actual reason ?
I think you mean ObjectInputStream and BufferedInputStream (not readers).
ObjectInputStream wraps input stream and provides typed methods that allow reading data of certain type from the stream. For example readDouble(), readObject() etc.
BufferedInputStream does not provide additional API (comparing to regular InputStream). The only thing it does is buffering of data, i.e. it reads data chunk-by-chunk that is much more efficient way than reading byte-by-byte.
An InputStream is an abstract class that can be used to define any type of input stream, including reading from file systems, URLs, sockets, etc.
You don't actually create an InputStream, as it doesn't mean anything by itself. Rather, you create a type of InputStream that defines how to read/write a particular type of data, such as the suggested ObjectInputStream. This class defines that the data being written is a Java Object (that implements Serializable or Externalizable). There are other InputStreams that are used for generic file data, images, audio, and a whole range of other types.
There is no such thing as an ObjectInputStreamReader, unless you write a class like this yourself that has the purpose of writing to an ObjectInputStream.
Refer to the ObjectInputStream and InputStream Java docs for more enlightenment
Related
I need to read a binary file and save each byte into a byte array. I've read other stackoverflow posts on this topic, but cannot figure out why mine does not work. Here is what I have:
String fileOne = "file1.bin";
byte[] byteArray = new byte[1000];
try{
FileInputStream fileIS = new FileInputStream(fileOne);
ObjectInputStream is = new ObjectInputStream(fileIS);
is.read(byteArray);
is.close();
for(int i =0; i < byteArray.length; i++){
System.out.println(byteArray[i]);
}
}
catch (FileNotFoundException e){
e.toString();
System.exit(0);
}
catch (IOException io){
io.toString();
System.exit(0);
}
Here's a way to read the contents of a file into a byte array. FileInputStream is all you need – leave ObjectInputStream out of it (unless you are explicitly dealing with data that was created from an ObjectOutputStream, but that doesn't seem to be the case since you are calling println() on each byte).
public static void main(String[] args) {
String filename = "file1.bin";
try (FileInputStream fis = new FileInputStream(filename)) {
byte[] bytes = fis.readAllBytes();
for (byte b : bytes) {
System.out.print(b);
}
} catch (Exception e) {
e.printStackTrace();
}
}
A few things here:
omit using ObjectInputStream – not needed for reading byte data, and won't work unless the data was created by the corresponding output stream. From the Javadoc: "An ObjectInputStream deserializes primitive data and objects previously written using an ObjectOutputStream. "
use try with resources – it will close the associated stream for you
catch Exception – in the code you posted, you will only see info if FileNotFoundException or IOException is thrown. For anything else, your code doesn't handle them or print out any info.
I have stored multiple objects in Teacher ArrayList and I'm trying to deserialize it, but it shows the garbage value.
public void Write(){
try{
FileOutputStream fs=new FileOutputStream("S.txt");
ObjectOutputStream os=new ObjectOutputStream(fs);
os.writeObject(teachers);
os.close();
}catch(Exception e)
{System.out.println(e);}
}
public void Read(){
try
{
FileInputStream fis = new FileInputStream("E:\\Books\\OOP\\Teacher\\S.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
teachers = (ArrayList<Teacher>) ois.readObject();
for(Teacher i: teachers){
System.out.println(i.toString());
}
ois.close();
fis.close();
}catch(IOException ioe){
System.out.println("Error");
return;
}catch(ClassNotFoundException c){
System.out.println("Class not found");
return;
}
}
You are using object streams, which persist your serialized objects in binary, regardless of the extension of the file (which happens to be ".txt" here, ambiguously suggesting that it'll be a text file when written).
You cannot view anything human-like from your file with a text editor when the data written is binary data.
If your "garbage values" also get printed when you iterate your List<Teacher> upon de-serialization, it implies that:
(De-)serialization actually succeeded (i.e. you've written your List<Teacher> to file and retrieved it)
Your Teacher class might not override toString properly or at all, so it prints the Type#hashCode notation from Object#toString when fed to the system output print stream
I'm trying to write a Java Android program that can read and write to a file. I'm having some issues though. When the line at the very end is run, Eclipse tells me that my totalString variable may not have been initialized. However, I assign it a value inside the try loop. When I remove that last line and run my program, my console displays "Read File Successfully", as well as "java.io.FileInputStream#d77ffd1". That's definitely not the value I wrote to the file. I don't know what I'm doing wrong here and I'm kind of losing my mind lmao. Additionally, if I try to put a line like
totalString = "A Test Value"
In the try block, I still get the same error. Any help would be greatly appreciated.
//lets try WRITING the file
Context context = getApplicationContext();
String filename = "balance";
String balanceString = "0.00";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(balanceString.getBytes());
outputStream.close();
}
catch (Exception e) {
e.printStackTrace();
System.out.println("Error in Writing File.");
}
//lets try READING the file
String totalString;
FileInputStream inputStream;
try {
inputStream = openFileInput(filename);
inputStream.read();
inputStream.close();
totalString = inputStream.toString();
System.out.println("Read File Successfully");
System.out.println(totalString);
}
catch (Exception e) {
e.printStackTrace();
System.out.println("Error in Reading File.");
}
System.out.println(totalString);
inputStream.toString() returns a string representing the id of the InputStream object. Not the data inside the file.
If you want the data inside the File which you are reading from the InputStream, you need to use built-in methods to read the file. The easiest way to do so is to wrap the InputStream object inside a BufferedReader (or any other Reader object), then use the .readLine() (or equivalent) method to get the data.
For example:
String totalString;
BufferedReader in;
try {
in = new BufferedReader(new InputStreamReader(openFileInput(filename)));
totalString = in.readLine();
in.close();
System.out.println("Read File Successfully");
System.out.println(totalString);
}
catch (Exception e) {
e.printStackTrace();
System.out.println("Error in Reading File.");
}
Now for output:
You could use the exact same technique as before, only changing the objects to their 'Writer' equivalents. For example:
PrintWriter out;
try {
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(penFileOutput(filename, Context.MODE_PRIVATE))));
out.println(balanceString);
out.flush();
out.close();
}
catch (Exception e) {
e.printStackTrace();
System.out.println("Error in Writing File.");
}
The purpose of using the PrintWriter here in addition to the BufferedWriter is because it provides very easy to use methods (i.e. println()). Also, the 'flush()' method is used to make sure all the data in the stream gets written to the file, rather than 'getting stuck' in the buffer.
EDIT: Forgot to add a 'new' before the BufferedReader above. Fixed.
inputStream.read() MIGHT throw an Exception. In this case, the variable MIGHT not have be initialized. Just change the declaration to
String totalString = null;
Alternatively you can move the System.out.println to the end of the try-block, where, when reached because no Exception is thrown, the variable is initialized.
Also, read some tutorials about reading and writing files.
inputStream.read() will read a byte from the stream. But if you don't assign the return value of that function to a variable, it is discarded.
inputStream.toString() does what it says. It tries to describe the object, not the contents of the stream.
I would do it like that
FileOutputStream outputStream=new FileOutputStream(filename);
ObjectOutputStream stringSaver = new ObjectOutputStream(outputStream);
stringSaver.writeObject(balanceString);
stringSaver.close();
outputStream.close();
All this in a try catch for saving in a file the String then load it with
FileInputStream inputStream = new FileInputStream(filename);
ObjectInputStream objectStream = new ObjectInputStream(inputStream);
totalString = (String) objectStream.readObject();
objectStream.close();
inputStream.close();
this also in try catch...
It should work.
The problem solves that there was one variable may not have been initialized.
When you dont understand one part of the code be free to ask :D
I have to use a method whose signature is like this
aMethod(FileInputStream);
I call that method like this
FileInputStream inputStream = new FileInputStream(someTextFile);
aMethod(inputStream);
I want to remove/edit some char which is being read from someTextFile before it being passed into aMethod(inputStream);
I cannot change aMethod's signature or overload it. And, it just take a InputStream.
If method taking a string as param, then I wouldn't be asking this question.
I am InputStream noob. Please advise.
you can convert a string into input stream
String str = "Converted stuff from reading the other inputfile and modifying it";
InputStream is = new ByteArrayInputStream(str.getBytes());
Here is something that might help. It will grab your .txt file. Then it will load it and go through line by line. You have to fill in the commented areas to do what you want.
public void parseFile() {
String inputLine;
String filename = "YOURFILE.txt";
Thread thisThread = Thread.currentThread();
ClassLoader loader = thisThread.getContextClassLoader();
InputStream is = loader.getResourceAsStream(filename);
try {
FileWriter fstream = new FileWriter("path/to/NEWFILE.txt");
BufferedWriter out = new BufferedWriter(fstream);
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
while((inputLine = reader.readLine()) != null) {
String[] str = inputLine.split("\t");
if(/* IF WHAT YOU WANT IS IN THE FILE ADD IT */) {
// DO SOMETHING OR ADD WHAT YOU WANT
out.append(str);
out.newLine();
}
}
reader.close();
out.close();
} catch (Exception e) {
e.getMessage();
}
}
Have you looked at another class FilterInputStream which also extends InputStream which may fit into your requirement?
From the documentation for the class
A FilterInputStream contains some other input stream, which it uses as its basic source of data, possibly transforming the data along the way or providing additional functionality.
Also have a look at this question which also seems to be similar to your question.
Is there a reliable way to convert any object to a String and then back again to the same Object? I've seen some examples of people converting them using toString() and then passing that value into a constructor to reconstruct the object again but not all objects have a constructor like this so that method wont work for all cases. What way will?
Yes, it is called serialization!
String serializedObject = "";
// serialize the object
try {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream so = new ObjectOutputStream(bo);
so.writeObject(myObject);
so.flush();
serializedObject = bo.toString();
} catch (Exception e) {
System.out.println(e);
}
// deserialize the object
try {
byte b[] = serializedObject.getBytes();
ByteArrayInputStream bi = new ByteArrayInputStream(b);
ObjectInputStream si = new ObjectInputStream(bi);
MyObject obj = (MyObject) si.readObject();
} catch (Exception e) {
System.out.println(e);
}
This is the code:
try {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream so = new ObjectOutputStream(bo);
so.writeObject(stringList);
so.flush();
redisString = new String(Base64.encode(bo.toByteArray()));
}
catch (Exception e) {
e.printStackTrace();
}
try {
byte b[] = Base64.decode(redisString.getBytes());
ByteArrayInputStream bi = new ByteArrayInputStream(b);
ObjectInputStream si = new ObjectInputStream(bi);
List<String> stringList2 = (List<String>)si.readObject();
System.out.println(stringList2.get(1));
}
catch (Exception e) {
e.printStackTrace();
}
Serialize to byte array, convert to Base64. Then decode Base64 back to byte array and deserialize.
None will work in all cases. An object may, e.g., contain references to other JVMs handling their state, and this state may be not available for you to restore.
Additional problems you're going to meet will include open streams, listening sockets, and almost anything else from the outer world.
There's no need to repeat that most at least two of Java core engineers say that serialization was one of the greatest mistakes a single worst feature in Java, that is, after finalization. (I do love serialization nevertheless, it's handy. But it won't always work.)
One way is to use JSON. For implementation specific in Java, the answer might be given in this post:
java code corresponding to Newtonsoft.Json.JsonConvert.SerializeObject(Object source,Newtonsoft.Json.JsonSerializerSettings()) in .net?
Using JSON is reliable enough that it's used for web application development (Ajax).
Yes, it is Serialization You can use, ObjectInputStream.readObject and ObjectOutputStream.writeObject. Please see below example:
MyClass myClass = new MyClass();
FileOutputStream fileStream = new FileOutputStream("myObjectFile.txt");
ObjectOutputStream os = new ObjectOutputStream(fileStream);
os.writeObject(os);
os.close();
FileInputStream fileInStream = new FileInputStream("myObjectFile.txt");
ObjectInputStream ois = new ObjectInputStream(fileInStream);
MyClass myClass2 = ois.readObject();
ois.close();
You can use SerializationUtils from org.apache.commons.
It provides the methods serialize and deserialize