Java学习笔记——I/O流

时间:2023-03-09 18:44:50
Java学习笔记——I/O流

朝辞白帝彩云间,千里江陵一日还。
两岸猿声啼不尽,轻舟已过万重山。

              ——早发白帝城

我们老师写代码有个特点,就是简洁。每一句的意图都十分明确。所以他讲课的速度也比较快。

跑题了,说说I/O流:

1、字节输入流

2、字符输入流

3、字节输出流

4、字符输出流

上代码:

 public class FileInputStreamAndFileoutputSteamDemo {

     public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream("/home/yanshaochen/public/abc.txt");
byte[] bytes = new byte[];
bytes = "金麟岂是池中物,一遇风云变化龙".getBytes();
fos.write(bytes);
fos.close();
FileInputStream fis = new FileInputStream("/home/yanshaochen/public/abc.txt");
String str = "";
int data;
while ((data = fis.read(bytes)) != -) {
str += new String(bytes, , data);
}
System.out.println(str);
fis.close();
}
}
 public class WriterAndReader {

     public static void main(String[] args) throws IOException {
String path = "/home/yanshaochen/public/abc.txt";
Writer wt = new FileWriter(path);
String str = "AAAAA";
wt.write(str);
wt.close();
Reader rd = new FileReader(path);
char[] chars = new char[];
int data;
str = "";
while ((data = rd.read(chars))!=-) {
str += new String(chars, , data);
}
System.out.println(str);
rd.close();
}
}

带缓冲区的字符输入输出流

 public class BufferedReaderAndBufferedWriter {

     public static void main(String[] args) throws IOException {
Writer fw = new FileWriter("/home/yanshaochen/public/abc.txt");
BufferedWriter bw = new BufferedWriter(fw);
String str = "AAAAAAAA";
bw.write(str);
bw.newLine();
bw.close();
Reader fr =new FileReader("/home/yanshaochen/public/abc.txt");
BufferedReader br = new BufferedReader(fr);
while ((str = br.readLine())!= null) {
System.out.println(str);
}
br.close();
}
}

字节流读写二进制

 public class DataInputStreamDemo {

     public static void main(String[] args) throws IOException {
//原始地址
InputStream is = new FileInputStream("/home/yanshaochen/图片/2017-05-06 15-12-02屏幕截图.png");
DataInputStream dis = new DataInputStream(is);
//目标地址
OutputStream os = new FileOutputStream("/home/yanshaochen/public/2017-05-06 15-12-02屏幕截图.png");
DataOutputStream dos = new DataOutputStream(os);
byte[] bytes = new byte[];
int data;
while((data = dis.read(bytes)) != -){
dos.write(bytes,,data);
}
System.out.println("copy ok!");
dos.close();
dis.close();
}
}