J
js_dev
Writing to files
How do I write to a file in Java?
(a)
Using FileWriter:
import java.io.FileWriter; //import needed
String contents = .....; /* String to be written */
try{ /* try-catch will be required for compiling successfully */
FileWriter fw = new FileWriter(fullpath);
fw.write(contents);
fw.flush();
fw.close();
}catch(Exception e){System.out.println("Exception, text:" + e);}
(b)
import java.io.FileOutputStream; //import needed
String s = ..... ; /* String to be written */
try{
FileOutputStream fos = new FileOutputStream(fullpath);
for (int i=0; i<s.length();++i){
fos.write((byte)s.charAt(i));
}
fos.flush();
fos.close();
}catch(Exception e){System("Exception :"+ e);}
(c)
Appending to a file:
import java.io.FileWriter; //import needed
String fullpath = ..... ; /* fullpath to the file to be appended to */
String contents= .....; /* String to be written */
try{
FileWriter fw = new FileWriter(fullpath,true);
//append the string character by character
//because no String append method is given
for (int i=0; i<contents.length(); ++i){
fw.append(contents.charAt(i));
}
fw.flush();
fw.close();
}catch(Exception e){appendlog("Exception :" + e);}
How do I write to a file in Java?
(a)
Using FileWriter:
import java.io.FileWriter; //import needed
String contents = .....; /* String to be written */
try{ /* try-catch will be required for compiling successfully */
FileWriter fw = new FileWriter(fullpath);
fw.write(contents);
fw.flush();
fw.close();
}catch(Exception e){System.out.println("Exception, text:" + e);}
(b)
import java.io.FileOutputStream; //import needed
String s = ..... ; /* String to be written */
try{
FileOutputStream fos = new FileOutputStream(fullpath);
for (int i=0; i<s.length();++i){
fos.write((byte)s.charAt(i));
}
fos.flush();
fos.close();
}catch(Exception e){System("Exception :"+ e);}
(c)
Appending to a file:
import java.io.FileWriter; //import needed
String fullpath = ..... ; /* fullpath to the file to be appended to */
String contents= .....; /* String to be written */
try{
FileWriter fw = new FileWriter(fullpath,true);
//append the string character by character
//because no String append method is given
for (int i=0; i<contents.length(); ++i){
fw.append(contents.charAt(i));
}
fw.flush();
fw.close();
}catch(Exception e){appendlog("Exception :" + e);}