Selenium WebDriver Java Framework Course Limited Time Offer for $20

Selenium WebDriver Java Framework Course Limited Time Offer for $20

 

Print

Write a File with Output Stream Writer Java

Using OutputStreamWriter in java.io.File package, you can write a text file. See the example below. 

 

package com.seleniummaster.examplefile;

import java.io.*;

public class WriteToFileWithOutputStreamWriter {

    public static void main(String[] args)
    {
        try {
            WriteToFile("Hello Test","testfile.txt");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void WriteToFile(String fileContent, String fileName) throws IOException {
        String projectPath = System.getProperty("user.dir");
        String tempFile = projectPath + File.separator+fileName;
        File file = new File(tempFile);
        // if file does exists, then delete and create a new file
        if (file.exists()) {
            try {
                File newFileName = new File(projectPath + File.separator+ "backup_"+fileName);
                file.renameTo(newFileName);
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //write to file with OutputStreamWriter
        OutputStream outputStream = new FileOutputStream(file.getAbsoluteFile());
        Writer writer=new OutputStreamWriter(outputStream);
        writer.write(fileContent);
        writer.close();

    }
    }

Run the code and open the created file named "testfile.txt". You will see the text file content as below .

Hello Test