Here you can find the source of writeStringToFile(String content, File file)
Parameter | Description |
---|---|
content | the content to write to the file |
file | the file to write into |
Parameter | Description |
---|---|
IOException | an exception |
public static File writeStringToFile(String content, File file) throws IOException
//package com.java2s; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; public class Main { /**// w ww. jav a2s . com * Writes a string to a file creating the file if it does not exist. * * @param content * the content to write to the file * @param file the file to write into * @return * @throws IOException */ public static File writeStringToFile(String content, File file) throws IOException { write(content, openOutputStream(file)); return file; } /** * Writes chars from a <code>String</code> to bytes on an * <code>OutputStream</code> using the default character encoding of the * platform. * <p> * * @param data * the <code>String</code> to write, null ignored * @param output * the <code>OutputStream</code> to write to * @throws IOException */ public static void write(String data, OutputStream output) throws IOException { if (data != null) { output.write(data.getBytes()); } } /** * Opens a {@link FileOutputStream} for the specified file, checking and * creating the parent directory if it does not exist. * * @return a new {@link FileOutputStream} for the specified file * @throws IOException */ public static FileOutputStream openOutputStream(File file) throws IOException { if (file.exists()) { if (file.isDirectory()) { throw new IOException("File '" + file + "' exists but is a directory"); } if (file.canWrite() == false) { throw new IOException("File '" + file + "' cannot be written to"); } } else { File parent = file.getParentFile(); if (parent != null && parent.exists() == false) { if (parent.mkdirs() == false) { throw new IOException("File '" + file + "' could not be created"); } } } return new FileOutputStream(file); } }