what is the variable "data" storing in this java program? - java

My code is working. I just need to know about the role of a specific variable in the code.
I tried to print the value in the variable "data", but it gives me some numbers i cant understand.
public static void main(String[] args) throws IOException {
FileInputStream fileinputstream = new FileInputStream ("c:\\Users\\USER\\Desktop\\read.TXT");
FileOutputStream fileoutputstream = new FileOutputStream("c:\\Users\\USER\\Desktop\\write.TXT");
while (fileinputstream.available() > 0) {
int data = fileinputstream.read();
fileoutputstream.write(data);
}
fileinputstream.close();
fileoutputstream.close();
}

You can look at the docs for FileInputStream.read, which says:
Reads a byte of data from this input stream. This method blocks if no input is yet available.
Returns:
the next byte of data, or -1 if the end of the file is reached.
So the integer you got (i.e. the number stored in data) is the byte read from the file. Since your file is a text file, it is the ASCII value of the characters in that file (assuming your file is encoded in ASCII).

FileInputStream#read() reads a single byte of information from the underlying file.
Since these files are text files (according to their extensions), you probably should be using a FileInputStream, but a FileReader, to properly handle characters, and not the bytes that make them up.

fileinputstream.read() returns "the next byte of data, or -1 if the end of the file is reached."
You can read more here

Related

How to write array of bytes to a binary file in Java

How to write an array of bytes b[i] to a binary file in Java.
I need to write those bytes it into a "binary file" to be able to read it later using hex editor (AXE).
Some readers might be confused by "binary file", by binary file I don't mean a file filled by zeros and ones, I mean machine-readable form, something like this :
binary files in text editor
The hex editor suppose to read this data, hex editor
From what I understand I need to byte stream that data into a file
Is there a command I could use for this purpose.
Any code would be appreciated.
Just write the byte[] to a FileOutputStream pointing to the file:
private static void writeBytesToFile(byte[] b, String f) {
try (FileOutputStream out = new FileOutputStream(f)){
out.write(b);
}
catch (IOException e) {
e.printStackTrace();
}
}

Read a single line from a text file Java [duplicate]

Hey I'm trying to open a file and read just from an offset for a certain length!
I read this topic:
How to read a specific line using the specific line number from a file in Java?
in there it said that it's not to possible read a certain line without reading the lines before, but I'm wondering about bytes!
FileReader location = new FileReader(file);
BufferedReader inputFile = new BufferedReader(location);
// Read from bytes 1000 to 2000
// Something like this
inputFile.read(1000,2000);
Is it possible to read certain bytes from a known offset?
RandomAccessFile exposes a function:
seek(long pos)
Sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs.
FileInputStream.getChannel().position(123)
This is another possibility in addition to RandomAccessFile:
File f = File.createTempFile("aaa", null);
byte[] out = new byte[]{0, 1, 2};
FileOutputStream o = new FileOutputStream(f);
o.write(out);
o.close();
FileInputStream i = new FileInputStream(f);
i.getChannel().position(1);
assert i.read() == out[1];
i.close();
f.delete();
This should be OK since the docs for FileInputStream#getChannel say that:
Changing the channel's position, either explicitly or by reading, will change this stream's file position.
I don't know how this method compares to RandomAccessFile however.

how to write UTF8 data to xml file using RandomAccessFile?

When trying to write some UTF8 data to a file, I end up with some garbage in the file. The code is as follows
public static boolean saveToFile(StringBuffer buffer,
String fileName,
ArrayList exceptionList,
String className)
{
log.debug("In saveToFile for file [" + fileName + "]");
RandomAccessFile raf = null;
File file = new File(fileName);
File backupFile = new File(fileName+"_bck");
try
{
if (file.exists())
{
if (backupFile.exists())
{
backupFile.delete();
}
file.renameTo(backupFile);
}
raf = new RandomAccessFile(file, "rw");
raf.writeBytes(buffer.toString());
raf.close();
The output of buffer.toString() is
<?xml version="1.0" encoding="UTF-8"?>
<ivr>
<version>1.1</version>
<templateName>αβγδεζη
The data in the file however is
<?xml version="1.0" encoding="UTF-8"?>
<ivr>
<version>1.1</version>
<templateName>▒▒▒▒▒▒▒</templateName>
How can I make sure that data i nthe file itself is UTF8
I'm not surpised you get garbage:
raf.writeBytes(buffer.toString())
The documentation for RandomAccessFile.writeBytes(String) says (emphasis added):
Writes the string to the file as a sequence of bytes. Each character in the string is written out, in sequence, by discarding its high eight bits.
In a few circumstances, that operation will result in a correctly encoded file. But in most it won't. That writeBytes() method is a foolish design by the Java developers. You need to correctly encode your text as bytes in UTF-8, and then write those bytes.
Do you really need to operate on the file as a random access file. If not, just manipulate it with a Writer wrapping an OutputStream.
You could use Charset.encode(CharBuffer) to produce a ByteBuffer holding the encoded bytes, then write those bytes to the file:
raf.write(StandardCharsets.UTF_8.encode(buffer).array());
The Javadoc for RandomAccessFile states that for writeBytes()
Writes the string to the file as a sequence of bytes. Each character
in the string is written out, in sequence, by discarding its high
eight bits. The write starts at the current position of the file
pointer.
Assuming that discarding parts of your String isn't what you want, you should be using writeUtf():
Writes a string to the file using modified UTF-8 encoding in a
machine-independent manner.
String txt = buffer.toString();
raf.write(txt.getBytes(StandardCharsets.UTF_8));

Reading From a File of Numbers Using RandomAccessFile Java

I have an assignment to write some numbers in a text file using PrintStream and then reading from that same file using RandomAccessFile. While the writing part works as intended, I get the following output when running my code.
807416096
840971040
874525984
Exception in thread "main" java.io.EOFException
908080928
941635872
at java.io.RandomAccessFile.readInt(RandomAccessFile.java:776)
at Problema4.main(Problema4.java:21)
Java Result: 1
Here is the code:
import java.io.*;
import java.util.*;
public class Problema4 {
public static void main(String[] args) throws IOException, FileNotFoundException
{
PrintStream ps = new PrintStream(new FileOutputStream("fisiernou.txt"));
int i=0;
while (i<11)
{
ps.print(i);
ps.print(" ");
i++;
}
ps.close();
RandomAccessFile raf = new RandomAccessFile("fisiernou.txt", "r");
raf.seek(0);
//System.out.println(raf.readInt());
while (raf.getFilePointer()<raf.length())
System.out.println(raf.readInt());
raf.close();
}
}
You are writing integer as strings ( ps.print(i) ). If you write 1, in the file you are writting the ascii character of 1. Suposse this is the unique number we write, the file then have only one byte.
When reading, you are using raf.readInt(). This method reads 4 bytes and convert them to an integer. If now you try to read your file, this only contains one byte (the ascii character of 1), and then you get an EOF excepcion.
Use the same type of method for writting and reading. You can write with FileOutputStream.write(int).
RandomAccessFile.readInt() reads a binary 32-bit integer from the file. This means that it read 4 bytes and transform those 4 bytes into an int. It doesn't read the string representation of an int. Read its javadoc.
When your raf pointer is reading from the file, it is possible to hit an 'End of File' character. From the Java API:
"It is generally true of all the reading routines in this class that if end-of-file is reached before the desired number of bytes has been read, an EOFException (which is a kind of IOException) is thrown."
http://docs.oracle.com/javase/7/docs/api/java/io/RandomAccessFile.html

Reading and writing binary file in Java (seeing half of the file being corrupted)

I have some working code in python that I need to convert to Java.
I have read quite a few threads on this forum but could not find an answer. I am reading in a JPG image and converting it into a byte array. I then write this buffer it to a different file. When I compare the written files from both Java and python code, the bytes at the end do not match. Please let me know if you have a suggestion. I need to use the byte array to pack the image into a message that needs to be sent over to a remote server.
Java code (Running on Android)
Reading the file:
File queryImg = new File(ImagePath);
int imageLen = (int)queryImg.length();
byte [] imgData = new byte[imageLen];
FileInputStream fis = new FileInputStream(queryImg);
fis.read(imgData);
Writing the file:
FileOutputStream f = new FileOutputStream(new File("/sdcard/output.raw"));
f.write(imgData);
f.flush();
f.close();
Thanks!
InputStream.read is not guaranteed to read any particular number of bytes and may read less than you asked it to. It returns the actual number read so you can have a loop that keeps track of progress:
public void pump(InputStream in, OutputStream out, int size) {
byte[] buffer = new byte[4096]; // Or whatever constant you feel like using
int done = 0;
while (done < size) {
int read = in.read(buffer);
if (read == -1) {
throw new IOException("Something went horribly wrong");
}
out.write(buffer, 0, read);
done += read;
}
// Maybe put cleanup code in here if you like, e.g. in.close, out.flush, out.close
}
I believe Apache Commons IO has classes for doing this kind of stuff so you don't need to write it yourself.
Your file length might be more than int can hold and than you end up having wrong array length, hence not reading entire file into the buffer.

Categories