文本文件讀取方式一
import java.io.*;
class FileReaderDemo
{
public static void main(String[] args) throws IOException
{
//創建一個文件讀取流對象,和指定名稱的文件相關聯。
//要保證該文件是已經存在的,如果不存在,會發生異常FileNotFoundException
FileReader fr = new FileReader("demo.txt");
//調用讀取流對象的read方法。
//read():一次讀一個字符。而且會自動往下讀。
int ch = 0;
while((ch=fr.read())!=-1)
{
System.out.println("ch="+(char)ch)
}
/*
while(true)
{
int ch = fr.read();
if(ch==-1)
break;
System.out.println("ch="+(char)ch);
}
*/
fr.close();
}
}
文本文件讀取方式二
/*
第二種方式:通過字符數組進行讀取。
*/
import java.io.*;
class FileReaderDemo2
{
public static void main(String[] args) throws IOException
{
FileReader fr = new FileReader("demo.txt");
//定義一個字符數組。用於存儲讀到字符。
//該read(char[])返回的是讀到字符個數。
char[] buf = new char[1024];
int num = 0;
while((num=fr.read(buf))!=-1)
{
System.out.println(new String(buf,0,num));
}
fr.close();
}
}
練習
//讀取一個.java文件,並打印在控制檯上。
import java.io.*;
class FileReaderTest
{
public static void main(String[] args) throws IOException
{
FileReader fr = new FileReader("DateDemo.java");
char[] buf = new char[1024];
int num = 0;
while((num=fr.read(buf))!=-1)
{
System.out.print(new String(buf,0,num));
}
fr.close();
}
}
//將C盤一個文本文件複製到D盤。
/*
複製的原理:
其實就是將C盤下的文件數據存儲到D盤的一個文件中。
步驟:
1,在D盤創建一個文件。用於存儲C盤文件中的數據。
2,定義讀取流和C盤文件關聯。
3,通過不斷的讀寫完成數據存儲。
4,關閉資源。
*/
import java.io.*;
class CopyText
{
public static void main(String[] args) throws IOException
{
copy_2();
}
public static void copy_2()
{
FileWriter fw = null;
FileReader fr = null;
try
{
fw = new FileWriter("SystemDemo_copy.txt");
fr = new FileReader("SystemDemo.java");
char[] buf = new char[1024];
int len = 0;
while((len=fr.read(buf))!=-1)
{
fw.write(buf,0,len);
}
}
catch (IOException e)
{
throw new RuntimeException("讀寫失敗");
}
finally
{
if(fr!=null)
try
{
fr.close();
}
catch (IOException e)
{
}
if(fw!=null)
try
{
fw.close();
}
catch (IOException e)
{
}
}
}
//從C盤讀一個字符,就往D盤寫一個字符。
public static void copy_1()throws IOException
{
//創建目的地。
FileWriter fw = new FileWriter("RuntimeDemo_copy.txt");
//與已有文件關聯。
FileReader fr = new FileReader("RuntimeDemo.java");
int ch = 0;
while((ch=fr.read())!=-1)
{
fw.write(ch);
}
fw.close();
fr.close();
}
}