JAVA-字符流练习。(新手用于记录每天的作业)
参考手册:
关键字:
write() 写入存取
close() 结束
flush() 刷新缓冲区(缓冲区就是临时存放数据的区域。)
currentTimeMillis() 返回以毫秒为单位的当前时间
创建方法:
FileWriter fwr = new FileWriter("C:\\ja.txt");<br>创建对象,并且给对象指定路径。
实例:
<strong>//导入的包。</strong>
import java.io.*;
<strong>//创建的一个类。
</strong>public class ZFLlx {
<strong> //公共静态的主方法。</strong>
public static void main(String[] args)throws IOException{
<strong> //调用方法。</strong>
lx4();
}
public static void lx4(){
FileOutputStream fos = null;
try {
<strong> //指定盘符和文件。</strong>
fos = new FileOutputStream("C:\\ja.txt");
<strong> // 指定盘符内并且设置格式。(OutputStreamWriter字符输出流)</strong>
OutputStreamWriter sow = new OutputStreamWriter(fos,"UTF-8");
<strong> //添加。</strong>
sow.write("您好");
<strong> //结束释放资源。</strong>
sow.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void lx3() throws IOException {
<strong> //指定盘符和文件。</strong>
FileWriter fwr = new FileWriter("C:\\ja.txt");
<strong> //输入添加的字符串。</strong>
fwr.write("Qy97");
fwr.write("威武");
<strong> //创建字符数据类型,添加要输入的字符。</strong>
char[] c = {'a','b','c','d','e'};
<strong> //写入。</strong>
fwr.write(c);
<strong> //刷新缓冲区(缓冲区就是临时存放数据的区域。)</strong>
fwr.flush();
<strong> //结束释放资源。</strong>
fwr.close();
}
private static void lx2() throws IOException {
<strong> //计算开始的时间。返回的是以毫秒为单位的时间。(1秒为1000毫秒)</strong>
long l = System.currentTimeMillis();
<strong> //指定盘符和文件。</strong>
FileReader frr = new FileReader("C:\\ja.txt");
<strong> // 创建字符数组。char是字符类型,一次读1024个字符</strong>
char[] c = new char[1024];
<strong> //定义一个变量</strong>
int len = 0;
<strong> //创建while语句。</strong>
while ((len = frr.read(c))!=-1){
System.out.println(new String(c,0,len));
}
<strong> //结束释放资源。</strong>
frr.close();
<strong> //结束时间。</strong>
long ll = System.currentTimeMillis();
<strong> //结束时间减去开始时间就会得到运行时间。</strong>
System.out.println(ll-l);
}
public static void lx1() {
FileReader fir = null;
FileWriter fwr = null;
try {
fir = new FileReader("C:\\ja.txt");
fwr = new FileWriter("D:\\ja.txt");
char[] c = new char[2024*10];
int len = 0;
while ((len=fir.read(c))!=-1){
fwr.write(c,0,len);
<strong> //flush 用来刷新缓冲区的,只有字符流才需要刷新</strong>
fwr.flush();
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if (fir!=null){
try {
fir.close();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (fwr!=null){
try {
fwr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
}
执行结果
lx1:
lx2:
lx3:
lx4: