Example:
package com.w3schools;
import java.io.FileInputStream;
import java.io.InputStream;
public class FileToByteArray {
public static void main(String args[]){
String fileName = "D:/Test files/file 3.txt";
InputStream is = null;
try {
is = new FileInputStream(fileName);
byte content[] = new byte[2*1024];
int readCount = 0;
while((readCount = is.read(content)) > 0){
System.out.println(new String(content, 0, readCount-1));
}
} catch (Exception e) {
e.printStackTrace();
}
}
} |
package com.w3schools;
import java.io.FileInputStream;
import java.io.InputStream;
public class FileToByteArray {
public static void main(String args[]){
String fileName = "D:/Test files/file 3.txt";
InputStream is = null;
try {
is = new FileInputStream(fileName);
byte content[] = new byte[2*1024];
int readCount = 0;
while((readCount = is.read(content)) > 0){
System.out.println(new String(content, 0, readCount-1));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
Download this example.