why does readLong method cause EOFException? - java

It throws eof exception in line 10 when I execute the following code. It seems that it cannot execute the readLong method. What should I do?
try (DataOutputStream dataOutputStream=new DataOutputStream(new BufferedOutputStream(new
FileOutputStream("1.dat")));
DataInputStream dataInputStream=new DataInputStream(new BufferedInputStream(new
FileInputStream("C:\\Users\\Asus\\IdeaProjects\\Example" +
"\\1.dat")))){
dataOutputStream.writeLong(123);
dataOutputStream.writeChar('D');
dataOutputStream.writeUTF("Hello!");
System.out.println(dataInputStream.readLong());//exception occurse here
System.out.println(dataInputStream.readChar());
System.out.println(dataInputStream.readUTF());
}catch (IOException e){
e.printStackTrace();
}

the problem you are reading the file before writing on it. when you read the file it was empty. also the data are not saved to the file until the stream is closed. so if you want to read the written values you should close the input stream and then read the file.
also be careful that the output stream file path is different than the input stream
here an example:
try ( DataOutputStream dataOutputStream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("1.dat")))) {
dataOutputStream.writeLong(123);
dataOutputStream.writeChar('D');
dataOutputStream.writeUTF("Hello!");
dataOutputStream.close();
DataInputStream dataInputStream = new DataInputStream(new BufferedInputStream(new FileInputStream("1.dat")));
System.out.println(dataInputStream.readLong());
System.out.println(dataInputStream.readChar());
System.out.println(dataInputStream.readUTF());
} catch (IOException e) {
e.printStackTrace();
}

Related

How to read binary files in a string sequence of 1 and 0?

I've created a Huffman coding algorithm, and then I wrote binary code in String and put it in binary file using FileOutputStream and DataOutputStream.
But now I cant understand how to read it? I need to get 1 and 0 sequence from binary file.
There is no method like .readString() in DataInputStream
try{
FileChooser fileChooser = new FileChooser();
fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Binary", "*.bin"));
FileOutputStream fileOutputStream = new FileOutputStream(fileChooser.showSaveDialog(window));
DataOutputStream outputStream = new DataOutputStream(fileOutputStream);
outputStream.writeChars(Main.string_ready_encode);
}catch (IOException e){
e.printStackTrace();
}
Main.string_ready_encode contains ready sequence
The problem with your writing code is that you have specified no file format. We now can only read the file if we know how many bytes it has. If you do know that, you can read it by doing the following:
try (DataInputStream stream = new DataInputStream(new FileInputStream(f))) {
byte[] bytes = new byte[NUMBER_OF_BYTES];
stream.read(bytes);
String content = new String(bytes);
System.out.println(content);
} catch (IOException e) {
e.printStackTrace();
}
But I would actually advise you to rewrite you file with some known file format, like so:
try (Writer writer = new OutputStreamWriter(new FileOutputStream(f), Charsets.UTF_8)) {
writer.write(Main.stringReadyEncode, 0, Main.stringReadyEncode.length());
} catch (IOException x) {
e.printStackTrace();
}
And read it like you would read any other file:
try (BufferedReader r = Files.newBufferedReader(f.toPath(), Charsets.UTF_8)) {
String line;
while((line = r.readLine()) != null) {
// do whatever you want with line
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
Just make sure to replace Charsets.UTF_8 with whatever encoding you used while writing to the file.

What is the meaning of the compiler error "variable x may not have been initialized"

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

Java: Error with calling the WriteUTF method

I'm having problems with writing a 2d, user-inputted array to a text file. My code thus far (in the Saving method, at least) is:
`public static void Save(String[][] EntryList)
{
try {
String[][] content = EntryList;
File file = new File("CBB.dat");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
InputStream instream;
OutputStream outstream;
instream = new DataInputStream( new BufferedInputStream(new FileInputStream(file))); // buffers the data stream
outstream = new DataOutputStream( new BufferedOutputStream(new FileOutputStream(file)));
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter writer = new BufferedWriter(fw);
for (int row = 0; row < EntryList.length; ++row)
{
outstream.writeUTF(EntryList[row][1]);
outstream.writeUTF(EntryList[row][2]);
outstream.writeUTF(EntryList[row][3]);
outstream.writeUTF(EntryList[row][4]);
outstream.writeUTF(EntryList[row][5]);
}
outstream.close();
}catch (IOException e) {
e.printStackTrace();
}
}`
However, when I try to compile, I get the error that Java "cannot find symbol - method WriteUTF(String)"
Apparently there is no writeUTF defined for java.io.OutputStream.
You should probably declare outstream as DataOutputStream reference:
DataOutputStream outstream;
as the method writeUTF is defined for DataOutputStream.

Is it possible to create a File object from InputStream

Is there any way to create a java.io.File object from an java.io.InputStream ?
My requirement is reading the File from a RAR . I am not trying to write a temporary File, I have a file inside RAR archive which I am trying to read.
You need to create new file and copy contents from InputStream to that file:
File file = //...
try(OutputStream outputStream = new FileOutputStream(file)){
IOUtils.copy(inputStream, outputStream);
} catch (FileNotFoundException e) {
// handle exception here
} catch (IOException e) {
// handle exception here
}
I am using convenient IOUtils.copy() to avoid manual copying of streams. Also it has built-in buffering.
In one line :
FileUtils.copyInputStreamToFile(inputStream, file);
(org.apache.commons.io)
Since Java 7, you can do it in one line even without using any external libraries:
Files.copy(inputStream, outputPath, StandardCopyOption.REPLACE_EXISTING);
See the API docs.
Create a temp file first using org.apache.commons.io.
File tempFile = File.createTempFile(prefix, suffix);
tempFile.deleteOnExit();
FileOutputStream out = new FileOutputStream(tempFile);
IOUtils.copy(in, out);
return tempFile;
Easy Java 9 solution with try with resources block
public static void copyInputStreamToFile(InputStream input, File file) {
try (OutputStream output = new FileOutputStream(file)) {
input.transferTo(output);
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
java.io.InputStream#transferTo is available since Java 9.
If you do not want to use other libraries, here is a simple function to copy data from an InputStream to an OutputStream.
public static void copyStream(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
Now, you can easily write an Inputstream into a file by using FileOutputStream-
FileOutputStream out = new FileOutputStream(outFile);
copyStream (inputStream, out);
out.close();
If you are using Java version 7 or higher, you can use try-with-resources to properly close the FileOutputStream. The following code use IOUtils.copy() from commons-io.
public void copyToFile(InputStream inputStream, File file) throws IOException {
try(OutputStream outputStream = new FileOutputStream(file)) {
IOUtils.copy(inputStream, outputStream);
}
}

How to read data from file(.dat) in append mode

We have an application which requires us to read data from a file (.dat) dynamically using deserialization. We are actually getting first object and it throws null pointer exception and "java.io.StreamCorruptedException:invalid type code:AC" when we are accessing other objects using a "for" loop.
File file=null;
FileOutputStream fos=null;
BufferedOutputStream bos=null;
ObjectOutputStream oos=null;
try{
file=new File("account4.dat");
fos=new FileOutputStream(file,true);
bos=new BufferedOutputStream(fos);
oos=new ObjectOutputStream(bos);
oos.writeObject(m);
System.out.println("object serialized");
amlist=new MemberAccountList();
oos.close();
}
catch(Exception ex){
ex.printStackTrace();
}
Reading objects:
try{
MemberAccount m1;
file=new File("account4.dat");//add your code here
fis=new FileInputStream(file);
bis=new BufferedInputStream(fis);
ois=new ObjectInputStream(bis);
System.out.println(ois.readObject());
**while(ois.readObject()!=null){
m1=(MemberAccount)ois.readObject();
System.out.println(m1.toString());
}/*mList.addElement(m1);** // Here we have the issue throwing null pointer exception
Enumeration elist=mList.elements();
while(elist.hasMoreElements()){
obj=elist.nextElement();
System.out.println(obj.toString());
}*/
}
catch(ClassNotFoundException e){
}
catch(EOFException e){
System.out.println("end");
}
catch(Exception ex){
ex.printStackTrace();
}
After you read an object from the input stream, the stream points to the next object.
Try (without reading from ois before):
MemberAccount m1 = null;
while( (m1=ois.readObject()) != null){
System.out.println(m1.toString());
}
The grammar for serialized objects is defined as:
stream:
magic version contents
By using the append option (new FileOutputStream(file,true);) you create a file with this data:
stream:
magic version contents magic version contents magic version contents ....
This data does not conform to the specification and can't be decoded by ObjectInputStream.

Categories