Java Text File Write writeStringToFile(String s, String filename)

Here you can find the source of writeStringToFile(String s, String filename)

Description

writeStringToFile Write a string, which may include newline characters, line by line to the file specified by filename.

License

Apache License

Declaration

public static void writeStringToFile(String s, String filename) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.*;

public class Main {
    /**/*from  w w  w  . j a va  2 s  . com*/
     * writeStringToFile
     *
     * Write a string, which may include newline characters, line by line
     * to the file specified by filename.
     */
    public static void writeStringToFile(String s, String filename) throws IOException {
        String inputStr = s.trim();
        if (inputStr.length() == 0)
            throw new IOException("Input string contains no printable characters.");

        BufferedReader br = new BufferedReader(new StringReader(inputStr));
        BufferedWriter bw = new BufferedWriter(new FileWriter(filename));

        // Read the string line by line and write each to the output file.
        try {
            String line;

            while ((line = br.readLine()) != null) {
                // Ignore lines that are empty or only contain whitespace.
                line = line.trim();
                if (line.length() == 0)
                    continue;

                // Write line to output file
                bw.write(line);
                bw.newLine();
            }
        } finally {
            br.close();
            bw.close();
        }
    }
}

Related

  1. writeStringToFile(String path, String contents)
  2. writeStringToFile(String s, File f)
  3. writeStringToFile(String s, File f)
  4. writeStringToFile(String s, File f)
  5. writeStringToFile(String s, File file)
  6. writeStringToFile(String s, String filePathname)
  7. writeStringToFile(String sdat, File f)
  8. writeStringToFile(String str, File file)
  9. writeStringToFile(String str, File file)