一.文件以字节输入输出
-
文件以字节输入
利用FileInputStrea
来创造一个对象,参数是这个文件的位置
这个对象利用int read()
,read(byte b[])(读取b.length()个字节到数组b中)
,read(byte b[], int off, int len)读取len个字节,从数组的off位置开始存放到数组b中
函数来一个一个按顺序读取字节,直到返回值为-1,返回的是0~225之间的整数,这个整数是经过补零编码过的 -
文件以字节输出
利用FileOutputStrea
来创造一个对象,参数是存放流数据的位置,一般默认覆盖这个文件,如果写了第二个参数true
,则不会刷新这个文件
利用void write(int)
,write(byte b[])
,write(byte b[], int off, int len)
,来写入这个数据流,参数int
就是之前读取的int -
关闭流
每次使用完这个文件流,都要用close()
关闭
//将文件c:\\newfile.txt中保存的信息输入到屏幕
import java.io.*;
public class test {
public static void main(String args[])throws IOException
{
int ch;
//建立文件对象,打开一个文件
File file = new File("C:\\Users\\dell\\Desktop\\有蝠同享\\java\\课件\\ch08.Java输入输出系统\\我和我的祖国.txt");
File file1 = new File("C:\\Users\\dell\\Desktop\\有蝠同享\\java\\课件\\ch08.Java输入输出系统\\我和我的祖国1.txt");
//必须进行异常处理
try{
//建立文件输入流,并关联到已经建立的文件对象
FileInputStream fin = new FileInputStream(file);
// 建立输出流
FileOutputStream fout = new FileOutputStream(file1);
//读入第一个字符
ch=fin.read();
fout.write(ch);
//判断,若不到文件尾,就循环一次取一个字符打印出来
while(ch!=-1)
{
ch = fin.read();
fout.write(ch);
}
//用完文件输入流后必须关闭
fin.close();
fout.close();
}
catch(FileNotFoundException e)
{ System.out.println(e); }
catch(IOException e)
{ System.out.println(e); }
}
}
(读取文件时返回的字节)
二.文件字符流输入输出
- 文件字符输入
使用FileReader
创建对象,使用read()
返回Unicode码,-1结尾
最后要关闭 - 使用
FileWrite
创建对象,使用Write(int)
写入文件
最后要关闭
import java.io.*;
public class test
{
public static void main(String args[])throws IOException
{
try
{
FileReader fr = new FileReader("C:\\Users\\dell\\Desktop\\有蝠同享\\java\\课件\\ch08.Java输入输出系统\\我和我的祖国.txt");
FileWriter fw = new FileWriter("C:\\Users\\dell\\Desktop\\有蝠同享\\java\\课件\\ch08.Java输入输出系统\\我和我的祖国1.txt");
int i;
while ((i = fr.read()) != -1)
{
System.out.print((char) i);
fw.write(i);
}
fr.close();
fw.close();
}
catch (IOException e)
{
System.out.println(e);
}
}
}
三.BufferWrite和BufferReader
FileWriter filewriter = new FileWriter("C:\\Users\\dell\\Desktop\\2019215053 杨雨润\\学生系统\\学生成绩.txt",true);
BufferedWriter out = new BufferedWriter(filewriter); // 输出流
out.append(namefield.getText() + " " + Idfield.getText() + " " + scorefield.getText() + "\n");
先创建一个文件对象,如果不想覆盖的话,设置为true
利用BufferWrite
类来输出到文件
利用append()
或者write()
函数来写
读取文件
// 获取文件内容
FileReader fileReader = new FileReader("C:\\Users\\dell\\Desktop\\2019215053 杨雨润\\学生系统\\学生成绩.txt");
BufferedReader in = new BufferedReader(fileReader); // 读入流
读取文本内容可以使用下面这个函数,readline
返回一行,如果这一行没有内容了就返回null
while((score = in.readLine())!=null)
{
System.out.println(score)
}
四.DataoutputStream和DatasinputStrea
这个类的构造函数参数需要一个InputStream
或者OutputStream
的类
DataInputStream in= new DataInputStream(ct.getInputStream());
DataOutputStream out = new DataOutputStream(ct.getOutputStream());
传输的都是string
类型的内容,而且是整段发送,在聊天工具中比较适合,或者需要整个文本内容进行传输的时候比较方便。
readUTF
读取的必须是writeUTF
写下的字符串。
读取
message = in.readUTF();
输出
out.writeUTF("Client: " + message);