Question

can someone explain simply how to read a binary file and how to write to a...

can someone explain simply how to read a binary file and how to write to a binary file in java please
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Read and Write Binary Files :-

When reading and writing binary files:
It's a good idea to use the buffer (Default buffer size is 8K).
It's possible to use references to the abstract base classes, instead of references to specific concrete classes.
There's a need to pay attentive to the exceptions (IOException and FileNotFoundException)

For read and write binary files using both File I/O API and new File I/O API (NIO).
The API (classes in the java.io.* package) is perfect for manipulate the low-level binary I/O operations such as read and write exactly one byte at a time
The NIO API (classes in the java.nio.* package) is more convenient for reading and writing the whole binary file at once.

We often use byte streams to read and write data in binary format, exactly 8bits.
All byte stream classes are inherited from the abstract classes InputStream and OutputStream.


The abstract class InputStream defines 2 main methods for read bytes from the input stream:-
1) read(): reads one byte of data (returns the byte as an integer value. Return -1 if the end of the file is reached.)
2) read(byte[]): reads a chunk of bytes to the specified byte array up to the size of the array.
(This method returns -1 if there’s no more data or the end of the file is reached).

Similarly the abstract class OutputStream defines 2 main methods for write bytes to the output stream:-
1) write(int):- write the specified byte to the output stream.
2) write(byte[]):- write the specified array of bytes to the output stream.


Example:-
import java.io.*;
public class copyFile{
public static void main(String[] args) {
if (args.length < 2) {
System.out.println("Please provide both input & output files");
System.exit(0);
}
String inputFile = args[0];
String outputFile = args[1];
   //Exception for handling I/O requests
try (
InputStream inputStream = new FileInputStream(inputFile);
OutputStream outputStream = new FileOutputStream(outputFile);
){
int byteRead;

while ((byteRead = inputStream.read()) != -1) {
outputStream.write(byteRead);
}

} catch (IOException ex) {
ex.printStackTrace();
}
}
}

Command for compiling:-
compile before run :- javac copyFile.java
java copyFile java1st.zip java2nd.zip


Using BufferedInputStream and BufferedOutputStream is as same as the FileInputStream and FileOutputStream.
The only difference is that the buffered stream uses an array of bytes internally to buffer the input and output
to reduce the number of calls to the native API, hence it increases IO performance.

code :-
same as the above code but replaces the exception handling blocks with this.
try (
InputStream inputStream = new BufferedInputStream(new FileInputStream(inputFile));
OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));
) {

byte[] buffer = new byte[BUFFER_SIZE];

while (inputStream.read(buffer) != -1) {
outputStream.write(buffer);
}

} catch (IOException ex) {
ex.printStackTrace();
}

we can set the memory(buffer) size for the buffer like this
int bufferSize = 20384; // 20KB buffer size
InputStream inputStream = new BufferedInputStream(new FileInputStream(inputFile), bufferSize);
OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile), bufferSize);


The utility class files in the java.nio.file package provides the below methods for read and write binary data:-
1) readAllBytes(Path path1):- Reads all bytes from the file and returns an array of bytes.
This method is work for read small files, not large ones.
2) write(Path path1, byte[] bytes): writes an array of bytes to the file with some useful options like
CREATE, TRUNCATE_EXISTING, WRITE and APPEND.
Note that both methods close the input and output file after done and throw IOException in case of error.

code:-

import java.io.*;
import java.nio.file.*;
public class copyingFileNIO {
public static void main(String[] args) {
if (args.length < 2) {
System.out.println("Please provide both input & output files");
System.exit(0);
}
String inputFile = args[0];
String outputFile = args[1];
try {
long start1 = System.currentTimeMillis();
byte[] allBytes = Files.readAllBytes(Paths.get(inputFile));
Files.write(Paths.get(outputFile), allBytes);
long end1 = System.currentTimeMillis();
System.out.println("Copy in " + (end1 - start1) + " ms");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

Add a comment
Know the answer?
Add Answer to:
can someone explain simply how to read a binary file and how to write to a...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Write a java application to read in an attached CSV file and store the data items within a Binary...

    Write a java application to read in an attached CSV file and store the data items within a Binary Search Tree.

  • 3. Write a program to read a (binary) file of integers, sort the integers, and write...

    3. Write a program to read a (binary) file of integers, sort the integers, and write them back to the same file. Assume that all the numbers can be stored in an array. (Exercise 3) 4. Repeat exercise 3, but assume that only 20 numbers can be stored in memory (in an array) at any one time. Hint: you will need to use at least two additional files for temporary output. Please finish the question in C language programming, thank...

  • 1. write a java program using trees(binary search treee) to read integers from input file( .txt)...

    1. write a java program using trees(binary search treee) to read integers from input file( .txt) and add +1 to each number that you read from the input file. then copy result to another (.txt) file. example: if inpu File has numbers like 4787 79434 4326576 65997 4354 the output file must have result of 4788 79435 4326577 65998 4355 Note: there is no commas in between the numbers. dont give images or theory please.

  • Chapter-14: 1. 2. 3. how to create a binary file and use write and read operations....

    Chapter-14: 1. 2. 3. how to create a binary file and use write and read operations. how to use seekg and seekp how to update a file record.

  • Using Java how would I write a program that reads and writes from binary or text...

    Using Java how would I write a program that reads and writes from binary or text files and gives me an output similar to this? Example Output: --------------------Configuration: <Default>-------------------- Enter the file name: kenb Choose binary or text file(b/t): b Choose read or write(r/w): w Enter a line of information to write to the file: lasdklj Would you like to enter another line? Y/N only n Continue? (y/n)y Enter the file name: kenb Choose binary or text file(b/t): b Choose...

  • Can someone tell me how to read a text file of an article into a number...

    Can someone tell me how to read a text file of an article into a number of words count? 3. Write a program that reads a text file and generate a histogram of the lengths of the words con- tained in the file. You should test your program using the file "marktwain.txt" available at the d2l website. You may use the MatLab functions isletter) or isspace) to test the characters in the array and size ) to determine the array...

  • Write a C++ program that will read a large .txt file and will find the highest...

    Write a C++ program that will read a large .txt file and will find the highest and lowest voltage, along with the associated time and ampere. The text file is large 1,000,000 rows of data, so speed is a factor. Per some of my own research it may be best to use mmap (If I have the fastest program I will receive a significant amount of extra credit)? Someone also told me that binary can be fast, but I have...

  • A heap can be encoded either as an array, or as a full binary tree. For...

    A heap can be encoded either as an array, or as a full binary tree. For this question, write a function that takes the array representation of a heap and outputs its binary tree representation. More specifically, you should write a function with the specifications given below. Specifications for the function: # def arrayToTree(A, j): # input: array A representing a heap, an index j in [0:len(A)] # output: a Node object storing the heap with root j in the...

  • Write a program in C++ to: 1. Read all records from a binary file (also attached...

    Write a program in C++ to: 1. Read all records from a binary file (also attached to this email) to arrays; (the record structure: student number (20 bytes), grade (integer)) 2. Sort the list according to test scores; 3. Calculate the average test score for the class and print on the screen; 4. write sorted records to a new binary file. For example: The records in the original file: 1 89 2 95 3 76 The new file sorted by...

  • Please do in java as simply as possible with code available for copy and comments Write...

    Please do in java as simply as possible with code available for copy and comments Write a program that reads a file (provided as attachment to this assignment) and writes the file to a different file with line numbers inserted at the beginning of each line. Throw an exception if the file does not exist. An error message should result. For example if file input is: This is a test File output should be 1. This is a test I...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT