Here you can find the source of writeStringToFile(final String string, final File file)
Parameter | Description |
---|---|
string | The string to write |
file | The file to write to |
Parameter | Description |
---|---|
IOException | The file did not exist, or could not be created for writing. |
static void writeStringToFile(final String string, final File file) throws IOException
//package com.java2s; /*/*from w w w . java 2s. co m*/ * The contents of this file are subject to the terms of the Common Development and * Distribution License (the License). You may not use this file except in compliance with the * License. * * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the * specific language governing permission and limitations under the License. * * When distributing Covered Software, include this CDDL Header Notice in each file and include * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL * Header, with the fields enclosed by brackets [] replaced by your own identifying * information: "Portions Copyright [year] [name of copyright owner]". * * Copyright 2015 ForgeRock AS. */ import java.io.File; import java.io.IOException; import java.io.PrintWriter; public class Main { /** * Writes a string to a file. * @param string The string to write * @param file The file to write to * @throws IOException The file did not exist, or could not be created for writing. */ static void writeStringToFile(final String string, final File file) throws IOException { createFile(file); try (PrintWriter printWriter = new PrintWriter(file)) { printWriter.print(string); } } /** * Creates a file including parent directories if it does not yet exist. * @param file The file to create * @throws IOException Failed to create the file */ private static void createFile(File file) throws IOException { if (!file.exists()) { createDirectory(file.getParent()); if (!file.createNewFile()) { throw new IOException("Failed to create " + file.getPath()); } } } /** * Creates a directory unless it already exists. * @param directory The directory to create. * @throws IOException Failed to create directory. */ static void createDirectory(final String directory) throws IOException { File dir = new File(directory); if (!dir.exists()) { if (!dir.mkdirs()) { throw new IOException("Failed to create directory: " + directory); } } } }