package com.rockman.learn;
import java.io.*;
/**
* Created by jiuxiaosheng on 14-2-25.
*/
public class FileWrite {
/**
* 使用PrintWriter往文件中写入字符串内容
* @param filepath
* @param content
*/
public static void fileWrite1(String filepath, String content) {
try {
PrintWriter printWriter = new PrintWriter(new File(filepath));
try {
printWriter.print(content);
}finally {
printWriter.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
/**
* 使用OutputStreamWriter往文件写入字符串内容
* @param filepath
* @param content
*/
public static void fileWrite2(String filepath, String content) {
try {
FileOutputStream fos = new FileOutputStream(filepath);
OutputStreamWriter osw = new OutputStreamWriter(fos, "utf-8");
try {
osw.write(content);
osw.flush();
}finally {
osw.close();
fos.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 直接使用FileOutputStream写入字符串到文件
* @param filePath
* @param content
*/
public static void fileWrite3(String filePath, String content) {
try {
FileOutputStream fos = new FileOutputStream(filePath);
try {
fos.write(content.getBytes());
}finally {
fos.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 使用BufferedOutputStream写入字符串到文件
* @param filePath
* @param content
*/
public static void fileWrite4(String filePath, String content) {
try {
FileOutputStream fos = new FileOutputStream(filePath);
BufferedOutputStream bos = new BufferedOutputStream(fos);
try {
bos.write(content.getBytes());
bos.flush();
} finally {
bos.close();
fos.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 使用FileWriter写入字符串到文件
* @param filePath
* @param content
*/
public static void fileWrite5(String filePath, String content) {
try {
FileWriter fw = new FileWriter(filePath);
try {
fw.write(content);
fw.flush();
} finally {
fw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Java文件写入文本内容方法
最新推荐文章于 2023-03-01 11:10:05 发布
本文介绍了五种使用Java进行文件写入的方法,包括使用PrintWriter、OutputStreamWriter、FileOutputStream、BufferedOutputStream及FileWriter等API,并详细展示了每种方法的实现代码及异常处理。
摘要由CSDN通过智能技术生成