package cn.lianxi.test;
import org.junit.Test;
import java.io.*;
import java.nio.charset.StandardCharsets;
public class Demo {
@Test
public void test01() throws Exception {
File file = new File("file1.txt");
//如果不存在 就创建
if(!file.exists()){
file.createNewFile();
}
//创建in输入流
FileInputStream in = new FileInputStream(file);
int i = -1;
while ((i = in.read()) != -1){
System.out.println((char)i);
}
in.close();
}
@Test
public void test02() throws Exception {
//创建out输出流 append参数: 默认不写是false,改为true可追加写入
FileOutputStream out = new FileOutputStream("file1.txt",true);
//方式一
// out.write(97);
// out.write(97);
// out.write(97);
//方式二
// byte[] bytes = {12,23,45,56,63};
// out.write(bytes);
//方式三
byte[] bs1 = "abcdefg".getBytes(StandardCharsets.UTF_8);
out.write(bs1,0,3);//从索引off开始,写length个字节
for (int i = 0; i < 5; i++) {
out.write("hello".getBytes(StandardCharsets.UTF_8));
//换行的三种方式
out.write("rn".getBytes(StandardCharsets.UTF_8));
//out.write("n".getBytes(StandardCharsets.UTF_8));
//out.write("r".getBytes(StandardCharsets.UTF_8));
}
out.close();
}
@Test
public void test03() throws Exception{
//创建out输出流
FileOutputStream out = null; //append参数: 默认不写是false,改为true可追加写入
try {
out = new FileOutputStream("file1.txt", true);
//方式一
out.write(97);
out.write(97);
out.write(97);
}catch (IOException e){
e.printStackTrace();
}finally {
if(out!=null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Test
public void test04() throws Exception {
File file = new File("file2.txt");
//如果不存在 就创建
if(!file.exists()){
file.createNewFile();
}
//创建字节输入流
FileInputStream in = new FileInputStream(file);
//从这个输入流读取一个字节的数据。
int read = in.read();
System.out.println("read = " + read);
in.close();
}
@Test
public void test05() throws Exception {
File file = new File("file3.txt");
//如果不存在 就创建
if(!file.exists()){
file.createNewFile();
}
//创建字节输入流
FileInputStream in = new FileInputStream(file);
//从这个输入流读取一个字节的数据。
int read = in.read(); //int read ;
while(read != -1){ //while((read = in.read) != -1)
System.out.println((char)read);
read = in.read(); //
}
in.close();
}
@Test
public void test06() throws Exception {
File file1 = new File("file2.txt");
if(!file1.exists()){
file1.createNewFile();
}
File file2 = new File("file3.txt");
if(!file1.exists()){
file1.createNewFile();
}
FileInputStream in = new FileInputStream(file1);
FileOutputStream out = new FileOutputStream(file2);
int bys; //实际写入的字节数
//设置一个
byte[] bytes = new byte[1024];
while((bys = in.read(bytes)) != -1){
out.write(bys);
}
out.close();
in.close();
}
}