Created
March 25, 2013 11:43
-
-
Save ichaos/5236602 to your computer and use it in GitHub Desktop.
Java: Write to file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* In Java, BufferedWriter is a character streams class to handle the character data. | |
* Unlike bytes stream (convert data into bytes), you can just write the strings, arrays or characters data directly to file. | |
*/ | |
import java.io.BufferedWriter; | |
import java.io.File; | |
import java.io.FileWriter; | |
import java.io.IOException; | |
public class WriteToFileExample { | |
public static void main(String[] args) { | |
try { | |
String content = "This is the content to write into file"; | |
File file = new File("/users/filename.txt"); | |
// if file doesnt exists, then create it | |
if (!file.exists()) { | |
file.createNewFile(); | |
} | |
FileWriter fw = new FileWriter(file.getAbsoluteFile()); | |
BufferedWriter bw = new BufferedWriter(fw); | |
bw.write(content); | |
bw.close(); | |
System.out.println("Done"); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment