Here you can find the source of writeFileAsString(String filename, String contents)
Parameter | Description |
---|---|
filename | name of the file to write |
contents | contents of the file |
Parameter | Description |
---|---|
IOException | an exception |
public static void writeFileAsString(String filename, String contents) throws IOException
//package com.java2s; /******************************************************************************* * Copyright 2010 Dieselpoint, Inc./* w w w. ja v a 2s . 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.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; public class Main { /** * Write a String to disk using the specified filename and the default encoding. * @param filename name of the file to write * @param contents contents of the file * @throws IOException */ public static void writeFileAsString(String filename, String contents) throws IOException { writeFileAsString(filename, contents, null); } /** * Write a String to disk using the specified filename and optional encoding. * @param filename name of the file to write * @param contents contents of the file * @param encoding the charset, for example, "UTF-8" * @throws IOException */ public static void writeFileAsString(String filename, String contents, String encoding) throws IOException { File file = new File(filename); file.getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream(file); OutputStreamWriter writer; if (encoding == null) { writer = new OutputStreamWriter(fos); } else { writer = new OutputStreamWriter(fos, encoding); } writer.write(contents); writer.close(); fos.close(); } }