【Java学习笔记】基础知识学习17【文件文本读取写入】

我们写程序,就自然涉及到从文件中读取文本,或者将生成的文本内容输入到文件。

这里介绍几种方法来完成我们需要的功能

文件读取:

文件读取需要使用的一个类是File,一个类是FileInputStream(文件字节输入流)类

使用方法如下代码所示:

	static void FileRead(){
		File txtFile=new File("G:\\logic.txt");
		byte[] js=new byte[(int)(txtFile.length())];
		try {
			FileInputStream txtInput=new FileInputStream(txtFile);
			txtInput.read(js);
			String nTxt=new String(js);
			System.out.println(nTxt);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

还可以使用FileReader(文件字符输入流)类来实现文本的读取。

	static void FileReader(){
		File txtFile=new File("G:\\logic.txt");
		char[] js=new char[(int)(txtFile.length())];
		try {
			java.io.FileReader fRead=new java.io.FileReader(txtFile);
			try {
				fRead.read(js);
				String kkk=new String(js);
				System.out.println(kkk);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

文件写入:

使用FileOutputStream(文件字节输出流)类,加上File类辅助。

代码如下:

	static void CreatText(){
		File newFile=new File("G:\\re.txt");
		try {
			if(!newFile.exists()){
				newFile.createNewFile();
			}
			FileOutputStream outS=new FileOutputStream(newFile);
			byte[] buts="we are the world".getBytes();
			outS.write(buts);
			outS.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

再就是FileWriter文件字符输出流类:

	static void CreatTextChar() {
		File newFile = new File("G:\\re.txt");
		try {
			if (!newFile.exists()) {
				newFile.createNewFile();
			}
			FileWriter outS = new FileWriter(newFile);
			char[] buts = "we are the world".toCharArray();
			outS.write(buts);
			for (char c : buts) {
				outS.append(c);
			}
			outS.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

使用这个可以达到写入内容到文件的目的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值