Java Text File Write nio writeStringToFile(final File file, final String content)

Here you can find the source of writeStringToFile(final File file, final String content)

Description

write String To File

License

Apache License

Declaration

public static void writeStringToFile(final File file, final String content) throws IOException 

Method Source Code

//package com.java2s;
/**/*from  w  w  w  .  j  a  va 2  s.  com*/
 * NOTICE: MANY METHODS HERE ARE DIRECTLY REVERSED ENGINEERED FROM APACHE SOFTWARE FOUNDATION'S COMMONS-IO LIBRARY
 * https://github.com/apache/commons-io/blob/trunk/src/main/java/org/apache/commons/io/FileUtils.java
 * <p/>
 * You may obtain a copy of the License at
 * <p/>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p/>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.*;
import java.nio.charset.Charset;

public class Main {
    public static void writeStringToFile(final File file, final String content) throws IOException {
        if (content == null) {
            throw new UnsupportedOperationException("Cannot write null to file. Consider deleting it instead");
        }
        try (OutputStream fos = openOutputStream(file)) {
            fos.write(content.getBytes(Charset.forName("UTF-8")));
        }
    }

    public static FileOutputStream openOutputStream(final File file) throws IOException {
        if (file.exists()) {
            if (file.isDirectory()) {
                throw new IOException("File '" + file + "' exists but is a directory");
            }
            if (!file.canWrite()) {
                throw new IOException("File '" + file + "' cannot be written to");
            }
        } else {
            File parent = file.getParentFile();
            if (parent != null) {
                if (!parent.mkdirs() && !parent.isDirectory()) {
                    throw new IOException("Directory '" + parent + "' could not be created");
                }
            }
        }
        return new FileOutputStream(file);
    }
}

Related

  1. writeString(final File file, final String str)
  2. writeString(OutputStream buffer, String s)
  3. writeStringToFile(File file, String content, String value)
  4. writeStringToFile(File file, String string)
  5. writeStringToFile(File file, String text)
  6. writeStringToFile(String s, File f)
  7. writeTextFile(final File file, final String text)
  8. writeTextFile(String file, String articleContent)
  9. writeTo(File file, String content)