文件
字节流
- 抽象类: I n p u t S t r e a m InputStream InputStream、 O u t p u t S t r e a m OutputStream OutputStream
- 说明:常用于处理二进制文件,如图像、音频等。
前者为输入流,后者为输出流。输入流读出数据,输出流写入数据(输出到文件)。
import java.io.*;
public class FileTest { // 字节流,8位二进制
public static void main(String [] args) throws IOException
{
final String filePath = "test1.txt";
try(
FileInputStream fin = new FileInputStream(FileDescriptor.in); // 建立文件输入流接收键盘输入
FileOutputStream fout = new FileOutputStream(filePath); // 有则覆盖,无则创建
)
{
System.out.println("请输入要写入文件的内容,以#结束:");
char ch;
while((ch=(char)fin.read())!='#')
fout.write(ch);
}
catch(FileNotFoundException e)
{
System.out.println("文件" + filePath + "没有被找到!");
}
catch(IOException e) {}
try(
FileInputStream fin = new FileInputStream(filePath); // 输出文件内容
FileOutputStream fout = new FileOutputStream(FileDescriptor.out); // 建立文件输出流
)
{
System.out.println("文件" + filePath + "中的内容是:");
while(fin.available()>0) {
int data = fin.read(); // 读取文件内容
fout.write(data); // 以文件输出流输出数据
}
}
catch(IOException e) {}
}
}
字符流
- 抽象类: R e a d e r Reader Reader、 W r i t e r Writer Writer
- 说明:常用于处理字符文件,如文本。
import java.io.*;
public class Character { // 字符流,2字节
public static void main(String [] args) throws IOException
{
final String filePath = "test2.txt"; // 先创建再读取
try(
FileWriter fw = new FileWriter(filePath);
)
{
final String fileContent = "file content.";
fw.write(fileContent);
fw.close();
}
catch(IOException e) {}
try(
FileReader fr = new FileReader(filePath);
)
{
char [] chs = new char [500];
int num = fr.read(chs); // 返回文件字符数
String str = new String(chs, 0, num); // 转化为String类型
System.out.println("文件" + filePath + "内容为:");
System.out.println(str);
fr.close();
}
catch(IOException e) {}
}
}
缓冲区:
先将内容写到缓冲区,写完后将缓冲区的全部内容写到文件。(感觉有点类似于
c
a
c
h
e
cache
cache的作用)
import java.io.*;
public class Character { // 字符流,2字节
public static void main(String [] args) throws IOException
{
final String filePath = "test2.txt"; // 先创建再读取
try(
FileWriter fw = new FileWriter(filePath);
BufferedWriter bfd = new BufferedWriter(fw); // 缓冲区必须将之前创建的FileWriter作为参数
)
{
final String fileContent = "file content.";
bfd.write(fileContent);
bfd.flush(); // 将缓冲区内容写到文件
fw.close();
}
catch(IOException e) {}
try(
FileReader fr = new FileReader(filePath);
BufferedReader bdr = new BufferedReader(fr);
)
{
char [] chs = new char [500];
int num = bdr.read(chs); // 返回文件字符数
String str = new String(chs, 0, num); // 转化为String类型
System.out.println("文件" + filePath + "内容为:");
System.out.println(str);
fr.close();
}
catch(IOException e) {}
}
}