Example:
package com.w3schools;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
public class WriteByteToFileTest {
public static void main(String args[]){
OutputStream opStream = null;
try {
String strContent = "Test Content";
byte[] byteContent = strContent.getBytes();
File myFile = new File("D:/Test files/test.txt");
//check if file exist,
//otherwise create the file before writing
if (!myFile.exists()) {
myFile.createNewFile();
}
opStream = new FileOutputStream(myFile);
opStream.write(byteContent);
opStream.flush();
} catch (Exception e) {
e.printStackTrace();
} finally{
try{
if(opStream != null) {
opStream.close();
System.out.println("Successfully write "
+ "byte content to file.");
}
} catch(Exception ex){
ex.printStackTrace();
}
}
}
} |
package com.w3schools;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
public class WriteByteToFileTest {
public static void main(String args[]){
OutputStream opStream = null;
try {
String strContent = "Test Content";
byte[] byteContent = strContent.getBytes();
File myFile = new File("D:/Test files/test.txt");
//check if file exist,
//otherwise create the file before writing
if (!myFile.exists()) {
myFile.createNewFile();
}
opStream = new FileOutputStream(myFile);
opStream.write(byteContent);
opStream.flush();
} catch (Exception e) {
e.printStackTrace();
} finally{
try{
if(opStream != null) {
opStream.close();
System.out.println("Successfully write "
+ "byte content to file.");
}
} catch(Exception ex){
ex.printStackTrace();
}
}
}
}
Output:
Stored data in temporary file.
Successfully write byte content to file. |
Stored data in temporary file.
Successfully write byte content to file.
Download this example.