Java学习 FIleReader类

需求:读取一个文本文件,将读取的文件读取到控制台

        创建读取字符数据的流对象 在创建流对象是 必须确保被读取的文件 一定要存在

        用Reader的read方法读取字符  使用FileReader生成流对象

read()函数:

        作为整数读取的字符,范围在 0 到 65535 之间 (0x00-0xffff),如果已到达流的末尾,则返回 -1

        一次只能读取一个字符 可以使用for或者while循环来读取所有字符串

public class FileDemo
{

	public static void main(String[] args) throws IOException
	{

		FileReader fr = new FileReader("1.txt");	//开启一个关联1.txt的文件读取流
		int ch = 0;
		while ((ch = fr.read()) != -1)
		{
			System.out.print((char) ch);
		}
		fr.close();
		
		System.out.println();
		
		FileReader fr2 = new FileReader("1.txt");	//fr流已经关闭 不能再次使用fr 必须重新开启一个流
		int ch2 = 0;
		for(ch2 = fr2.read();ch2!=-1;ch2 = fr2.read())
		{
			System.out.print((char)ch2);
		}
		fr2.close();
	}

}

Reader类中还提供了read(char[] cbuf)

返回值:读取的字符数,如果已到达流的末尾,则返回 -1

read(char[] cbuf,int off,int len)

off是起始位置

len是在起始位置起再读取多少字符

返回值:读取的字符数,如果已到达流的末尾,则返回 -1

另外需要String的一个函数String(char[] ,int off,int len)


public class FileDemo
{

	public static void main(String[] args) throws IOException
	{

		FileReader fr = new FileReader("1.txt");	
		
		char[] ch = new char[6];
		int num = 0;
		
		while ((num = fr.read(ch))!=-1)
		{
			System.out.print(new String(ch, 0, ch.length));
		}
		
		
	}

}

将一个文件的内容复制到另一个文件中去

    1,读取要复制的文件

     2,将读取的文件写入另一个文件中去


public class FileDemo
{

	public static void main(String[] args) throws IOException
	{

		FileReader fr = new FileReader("1.txt");	
		FileWriter fw = new FileWriter("this_new.txt");
		int ch = 0;
		while((ch = fr.read())!=-1)
		{
			fw.write(ch);
		}
		
		fr.close();        //一定要记得最后要关闭文件 否则在缓冲区的内容不会复制过去 另外不关闭文件也不安全
                  fw.close();           	
}}
public class FileDemo
{

	public static void main(String[] args)
	{
		FileReader fr = null;
		FileWriter fw = null;
		try
		{
			fr = new FileReader("1.txt");
			fw = new FileWriter("1_1.txt");
			char[] buf = new char[2];
			int len = 0;
			while ((len = fr.read(buf)) != -1)
			{
				fw.write(buf, 0, len);
			}
		} catch (IOException e)
		{
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		finally
		{
			if(fr!=null)
				try
				{
					fr.close();
				} catch (IOException e)
				{
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}
			if(fw!=null)
				try
				{
					fw.close();
				} catch (IOException e)
				{
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}
		}
	}

} 


猜你喜欢

转载自blog.csdn.net/goddreamyyh/article/details/80855975