使用Java IO 实现简单文件读与写
package com.cn.test;
import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io.UnsupportedEncodingException;
public class FileTest {//定义一个文件对象,指定要对哪一个文件要进行文件操作static File path=new File("F:\\file\\test.txt");/*** @param args* @throws IOException* @throws UnsupportedEncodingException*/public static void main(String[] args) throws UnsupportedEncodingException, IOException {OutStream();InStram();InStreamReader();}
//使用字符流来输出获取的文件信息
public static void InStreamReader() throws IOException{//定义一个输入流用来获取指定文件中内容try {FileInputStream fis=new FileInputStream(path);//把字节流转换为字符流,字符编码为utf-8InputStreamReader isr=new InputStreamReader(fis,"utf-8");//把字符流放入到缓存流中BufferedReader br=new BufferedReader(isr);//读取缓存流中字符String myStr=br.readLine();System.out.println("读取的字符:"+myStr);} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}}//使用字节流输入读取文件中信息public static void InStram() throws IOException{try {//定义一个输入流用来获取指定文件中内容FileInputStream fis=new FileInputStream(path);byte[] b=new byte[1024];int len=0;while((len=fis.read())>0){fis.read(b, 0, len);String str=new String(b, 0, len);System.out.println(new String(str.getBytes(),"utf-8"));}} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}}//输出流方法public static void OutStream() throws UnsupportedEncodingException, IOException{String msg="这是使用字节输入流的方式输入到此txt文件中的";try {//定义一个输出流对象来输出到指定文件中FileOutputStream fos=new FileOutputStream(path);//写入到指定的文件中fos.write(msg.getBytes("utf-8"));//关闭输出流fos.close();} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}}
}
Java IO 实现简单文件读与写
最新推荐文章于 2022-09-24 16:45:36 发布