import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
//按照操作的最小单位:
//字节流:操作所有类型的数据
//字符流:操作文本类型的数据
//包装流:
// 数据流:操作常用数据类型
// 对象流:操作的对象(避免使用)
//流的数据类型:文件流:、
//FileInputStream
//InputStream:
//read:读取一个字节的数据。
//读取-1结束
//available:返回当前剩余可读取的字节数
//close:关闭流,释放资源
//OutputStream:
// write:输入一个字节的数据
// close:关闭,释放资源
// flush:刷新流,强制写出所有缓存数据
public class Chatroom {
public String getText(String filename){
//创建文件
try{
InputStream in =new FileInputStream(filename);
//创建一个字节数组
int length=in.available();
byte[] buffer=new byte[length];
//读取文件
in.read(buffer);
//关闭流
in.close();
String text=new String(buffer);
return text;
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
return null;
}
public void writeText(String filename,String content){
try{
// 创建文件
OutputStream on=new FileOutputStream(filename);
// 创建一个字节数组
byte[] content_1=content.getBytes();
String as=new String(content_1);
System.out.println(as);
// 输入文件
on.write(content_1);
// 关闭流
on.close();
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
public static void main(String[] args){
Chatroom cr=new Chatroom();
String text_1=cr.getText("abc.txt");
// System.out.println(text_1);
cr.writeText("abcd.txt",text_1);
String text_2=cr.getText("abcd.txt");
System.out.println(text_2);
System.out.println("传输完成");
}
}
bug:读取文字时会出现乱码
可改进的地方,读取保存文件可添加选择器,读取保存功能可设置监听器