JAVA——写入指定文本内容(字符)

版权声明:DY https://blog.csdn.net/Atishoo_13/article/details/82694732

#JAVA——写入指定文本内容(字符)


1.要求

以文本方式向某一指定路径指定文件名的文本文件写入指定文本内容。

2.方法

  • WriteFileByBytes()方法以字节为单位将内容写到文件中。通过FileOutputStream的write()方法将指定数组字节写入缓冲的输出流中。

  • 用JAVA写文件有很多方法,对于不同类型的数据,有不同的写入方法的技术要点如下:
    (1)FileOutputStream打开文件输出流,通过write方法以字符为单位写入文件,是写文件最通用的方法,能写入任何类型的文件,特别适合写二进制数据文件。
    (2)OutputStreamWriter打开文件输入流,通过write方法以字符为单位写入文件,能够将字符数组和字符串写入文件。
    (3)PrintWriter打开文件输出流,通过print和println方法写字符串到文件,与System.out的用法相似,常用于写入格式化的文本。
    (4)当文件写完后关闭输出流。

3.代码

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class rw13 {  //操作多种方式写文件的类
	public static void writeFileByBytes(String fileName) { //以字节为单位写入文件
		File file= new File(fileName);   //创建一个文件
		OutputStream out =null;
		try {
			out=new FileOutputStream(file);  //打开文件输出流
			String content="枫桥夜泊 \r\n张继\r\n月落乌啼霜满天,\r\n江枫渔火对愁眠。\r\n姑苏城外寒山寺,\r\n夜半钟声到客船。\r\n";
			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 el) {
				}
			}
		}
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String fileName = "D:\\office\\学前任务\\工程训练\\工程训练代码\\fqyb.txt";//写文件存入目录
		System.out.println("以字节为单位:");
		rw13.writeFileByBytes(fileName);  //调用方法写文件

	}

}

4.结果

  • 编译结果如下图所示:
    这里写图片描述
  • 运行结果如下图所示:
    这里写图片描述
  • 输出文件如下图所示:
    这里写图片描述

5.注意

newLine在使用中可能会出现问题:
不同系统的换行符:

  • windows --> \r\n
  • Linux --> \r
  • mac --> \n

猜你喜欢

转载自blog.csdn.net/Atishoo_13/article/details/82694732