Java Text File Write writeString(final String s, final File f)

Here you can find the source of writeString(final String s, final File f)

Description

Writes the specified string to the specified file.

License

Open Source License

Parameter

Parameter Description
s String to be written.
f File to be written to.

Declaration

public static void writeString(final String s, final File f) 

Method Source Code

//package com.java2s;
/*//from  w  w w .j  a va  2  s .  co  m
 *  Copyright (C) 2010 vektor
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.io.File;

import java.io.IOException;

import java.io.PrintWriter;

public class Main {
    /**
     * Writes the specified string to the specified file. It tries to create all
     * the necessary folders on the way to the file.
     *
     * @param s String to be written.
     * @param f File to be written to.
     */
    public static void writeString(final String s, final File f) {
        assureParentsExist(f);
        PrintWriter pw = null;
        try {
            pw = new PrintWriter(f);
            pw.write(s);
        } catch (final IOException e) {
            throw new RuntimeException(e);
        } finally {
            pw.close();
        }
    }

    private static void assureParentsExist(final File f) {
        final File parentDir = f.getParentFile();
        if (!parentDir.exists() || !parentDir.isDirectory()) {
            parentDir.mkdirs();
        }
    }
}

Related

  1. writeString(FileWriter fw, String s)
  2. writeString(final ObjectOutput objectOut, final String str)
  3. writeString(final ObjectOutput out, final String s)
  4. writeString(final String data, final int length, final byte[] destination, int offset)
  5. writeString(final String output, final String fileName)
  6. writeString(String a, String MyFilePath)
  7. writeString(String content, String path, String charset)
  8. writeString(String contents, File file)
  9. writeString(String contents, File file)