Java Exercises: Read contents from a file into byte array
Java Input-Output: Exercise-10 with Solution
Write a Java program to read contents from a file into byte array.
Sample Solution:
Java Code:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
// Reading contents from a file into byte array.
public class Exercise10 {
public static void main(String a[]){
String file_name = "/home/students/test.txt";
InputStream fins = null;
try {
fins = new FileInputStream(file_name);
byte file_content[] = new byte[2*1024];
int read_count = 0;
while((read_count = fins.read(file_content)) > 0){
System.out.println(new String(file_content, 0, read_count-1));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try{
if(fins != null) fins.close();
} catch(Exception ex){
}
}
}
}
Sample Output:
Welcome to w3resource.com. Append this text.Append this text.Append this text. Append this text. Append this text. Append this text. Append this text.
Flowchart:
JavaCode Editor:
Contribute your code and comments through Disqus.
Previous: Write a Java program to get file size in bytes, kb, mb.
Next: Write a Java program to read a file content line by line.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Java: Tips of the Day
How to sort an ArrayList?
Collections.sort(testList); Collections.reverse(testList);
That will do what you want. Remember to import Collections though!
Ref: https://bit.ly/32urdSe
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework