Here you can find the source of writeFile(String filePath, String text)
Parameter | Description |
---|---|
filePath | the path to the file. |
text | the string to write. |
Parameter | Description |
---|---|
IOException | an exception |
public static void writeFile(String filePath, String text) throws IOException
//package com.java2s; /*//from ww w . j av a2 s . c o m * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * 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.File; import java.io.IOException; import java.nio.charset.Charset; import com.google.common.io.Files; public class Main { /** * Writes a string to the specified file using the default encoding. * * If the file path doesn't exist, it's created. * If the file exists, it is overwritten. * * @param filePath the path to the file. * @param text the string to write. * @throws IOException */ public static void writeFile(String filePath, String text) throws IOException { writeFile(filePath, text, null); } /** * Writes a string to the specified file using the specified encoding. * * If the file path doesn't exist, it's created. * If the file exists, it is overwritten. * * @param filePath the path to the file. * @param text the string to write. * @throws IOException */ public static void writeFile(String filePath, String text, String encoding) throws IOException { File file = new File(filePath); File parent = file.getParentFile(); if (!parent.exists()) { parent.mkdirs(); } Charset charset = charsetForNameOrDefault(encoding); Files.write(text, file, charset); } private static Charset charsetForNameOrDefault(String encoding) { Charset charset = (encoding == null) ? Charset.defaultCharset() : Charset.forName(encoding); return charset; } }