0% found this document useful (0 votes)
28 views

Writing A File

This Java code sample demonstrates how to write a string of text content to a new file. It imports necessary file writing classes, declares a string variable to hold the content, creates a new file object if it doesn't already exist, gets a FileWriter and BufferedWriter to write to the file, writes the content string to the file, closes the writers, and prints a message if completed successfully.

Uploaded by

XXX
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Writing A File

This Java code sample demonstrates how to write a string of text content to a new file. It imports necessary file writing classes, declares a string variable to hold the content, creates a new file object if it doesn't already exist, gets a FileWriter and BufferedWriter to write to the file, writes the content string to the file, closes the writers, and prints a message if completed successfully.

Uploaded by

XXX
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

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/mkyong/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();

You might also like