演示对已有文件的数据续写 代码:
import java.io.*;
public class code
{
public static void main(String[] args) {
//传递一个true参数,代表不覆盖已有的文件,并在已有文件的末尾处进行数据续写
FileWriter fw = null;
try {
fw = new FileWriter("demo.txt",true);
fw.write("asdfg\r\n666");
} catch (IOException e) {
System.out.println(e.toString());
}
finally {
try {
if(fw!=null)//必须要判断,分别关闭
fw.close();
} catch (IOException e) {
System.out.println(e.toString());
}
}
}
}
文本文件读取方式一 代码:
import java.io.*;
public class code
{
public static void main(String[] args) throws IOException {
//创建一个文件读取流对象,和指定名称的文件相关联
//要保证该文件是已经存在的,如果不存在会发生异常FlieNotFoundException
FileReader fr = new FileReader("demo.txt");
//调用读取流对象的read方法
//read():一次读一个字符,而且会自动往下读
//int ch = fr.read();
//System.out.println((char)ch);
int ch = 0;
while((ch=fr.read())!=-1) {
System.out.print((char)ch);
}
/*
while(true)
{
int ch = fr.read();
if(ch==-1)
break;
System.out.println((char)ch);
}
*/
fr.close();
}
}
文本文件读取方式二 代码:
import java.io.*;
public class code
{
public static void main(String[] args) throws IOException {
//通过字符数组进行读取
FileReader fr = new FileReader("demo.txt");
//定义一个字符数组,用于存储读到的字符
//该read(char[])返回的是读到字符的个数
char[] buf = new char[1024];//2k
int num = 0;
while((num=fr.read(buf))!=-1) {
System.out.println(new String(buf,0,num));
}
fr.close();
}
}
练习:读取一个 .java文件,并打印在控制台上。
代码:
import java.io.*;
public class code
{
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader("demo.java");
char[] buf = new char[1024];
int num = 0;
while((num=fr.read(buf))!=-1) {
System.out.println(new String(buf,0,num));
}
fr.close();
}
}