1.1.字节流复制文件
public class Demo1 {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("day11_myIO\\a.txt");
BufferedInputStream bis = new BufferedInputStream(fis);
FileOutputStream fos = new FileOutputStream("day11_myIO\\b.txt");
BufferedOutputStream bos = new BufferedOutputStream(fos);
byte[] bytes = new byte[1024];
int len =bis.read(bytes);
while (len!=-1){
bos.write(bytes,0,len);
len =bis.read();
}
bos.close();
bis.close();
}
}
1.2.字节流捕获异常
public class Demo2 {
public static void main(String[] args) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream("day11_myIO\\a.txt");
fos.write("hello".getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
1.3.字节输入流读取数据并打印至控制台
public class Demo1 {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("day11_myIoByteStream\\a.txt");
byte[] bytes = new byte[1024];
int len = fis.read(bytes);
while (len!=-1){
String str = new String(bytes, 0, len);
System.out.println(str);
len = fis.read(bytes);
}
fis.close();
}
}
打印结果:
------------------------------------------------------------------------------
hello
world
java
2.1.字符流复制文件
public class Demo1 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("day12_myIoCharStream\\a.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("day12_myIoCharStream\\b.txt"));
String line = br.readLine();
while (line!=null){
bw.write(line);
bw.newLine();
bw.flush();
line = br.readLine();
}
bw.close();
br.close();
}
}
2.2.字符流读取文本学生信息,操作后再写入文本
public class Demo2 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("day12_myIoCharStream\\c.txt"));
ArrayList<Student> list = new ArrayList<Student>();
String line = br.readLine();
while (line!=null){
String[] strArr = line.split(",");
list.add(new Student(strArr[0],Integer.parseInt(strArr[1])));
line = br.readLine();
}
br.close();
Collections.sort(list,(o1, o2) -> o1.getAge()-o2.getAge());
BufferedWriter bw = new BufferedWriter(new FileWriter("day12_myIoCharStream\\d.txt"));
for (Student student : list) {
StringBuilder sb = new StringBuilder();
bw.write(sb.append(student.getName()).append(",").append(student.getAge()).toString());
bw.newLine();
bw.flush();
}
bw.close();
}
}
2.3.字符串解码
public class Demo1 {
public static void main(String[] args) throws UnsupportedEncodingException {
byte[] byte1 = "你好世界".getBytes("gbk");
System.out.println(Arrays.toString(byte1));
String s1 = new String(byte1);
String s2 = new String(byte1, "gbk");
System.out.println(s1);
System.out.println(s2);
}
}
打印结果:
-------------------------------------------------------------------------------
[-60, -29, -70, -61, -54, -64, -67, -25]
�������
你好世界