pada contoh program dibawah ini ada variabel String myContent dan sebuah file text newfile.txt pada drive C:/newfile.txt
oke berikut contoh programnya
Nama file : write_File.java
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class write_File {
public static void main(String[] args) {
BufferedWriter bw = null;
try {
String mycontent = "This String would be written" +
" to the specified File";
//Specify the file name and path here
File file = new File("C:/newfile.txt");
/* This logic will make sure that the file
* gets created if it is not present at the
* specified location*/
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file);
bw = new BufferedWriter(fw);
bw.write(mycontent);
System.out.println("File written Successfully");
} catch (IOException ioe) {
ioe.printStackTrace();
}
finally
{
try{
if(bw!=null)
bw.close();
}catch(Exception ex){
System.out.println("Error in closing the BufferedWriter"+ex);
}
}
}
}
output
jika pada file "newfile.txt" sebelumnya sudah ada kontennya/isi nya maka konten akan di tulis ulang/ konten lama akan dihapus dan diganti konten dari program ini
Program dibuat menggunakan netbeans
selamat mencoba,semoga bermanfaat ...
No comments:
Post a Comment