package toolClass;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import java.io.OutputStreamWriter;import java.io.PrintWriter;import java.io.Writer;/*** 多种方式写文件*/public class WriteToFile {/*** 以字节为单位写文件。适合于写二进制文件。如图片等* @parme fileName:文件名 content:写入的内容*/public void writeFileByBytes(String fileName,String content){File file = new File(fileName);OutputStream out= null;try {// 打开文件输出流out = new FileOutputStream(file);byte[] bytes = content.getBytes();//写入文件out.write(bytes);System.out.println("写文件" + file.getAbsolutePath() + "成功!");} catch (IOException e){System.out.println("写文件" + file.getAbsolutePath() + "失败!");e.printStackTrace();} finally {if (out != null){try {//关闭输出文件流out.close();} catch (IOException e1) {}}}}/*** 以字符为单位写文件。*/public void writeFileByChars(String fileName){File file = new File(fileName);Writer writer = null;try {//打开文件输出流writer = new OutputStreamWriter(new FileOutputStream(file));String content = "写入文件内容:\n1,The First line;\n2,The second line.";writer.write(content);System.out.println("写文件" + file.getAbsolutePath() + "成功!");} catch (IOException e){System.out.println("写文件" + file.getAbsolutePath() + "失败!");e.printStackTrace();} finally {if (writer != null){try {//关闭输出文件流writer.close();} catch (IOException e1) {}}}}/*** 以行为单位写文件*/public void writeFileByLines(String fileName){File file = new File(fileName);PrintWriter writer = null;try {writer = new PrintWriter(new FileOutputStream(file));//写字符串writer.println("写入文件内容:");//能写各种基本类型数据writer.print(true);writer.print(155);//换行writer.println();//写入文件writer.flush();System.out.println("写文件" + file.getAbsolutePath() + "成功!");} catch (FileNotFoundException e) {System.out.println("写文件" + file.getAbsolutePath() + "失败!");e.printStackTrace();} finally {if (writer != null){//关闭输出文件流writer.close();}}}}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。