字节输出流,输出到对应的文件中
public class FileOutputStreamDemo {
public static void main(String[] args) throws Exception {
//1.创建目标对象
File target = new File("H:/xinyi/stream/OutputStrean.txt");
//2.创建字节输出流对象
OutputStream out = new FileOutputStream(target);
//3.具体操作
out.write("HelloKitty".getBytes(),5, 5);
//关闭流
out.close();
}
}
字节输入流:
public class FileInputStreamDemo {
public static void main(String[] args) throws Exception {
//1.创建源
File resources = new File("H:/xinyi/stream/OutputStrean.txt");
//2.创建字节输入流,并连接源
InputStream in = new FileInputStream(resources);
//3.具体的读取操作
byte[] buffer = new byte[5];
int len = -1;
//in.read(buffer) 读取多个字节,并且存储到buffer数组中,返回读取字节的个数
while ((len = in.read(buffer)) != -1) {
String str = new String(buffer, 0,len);
System.out.println(str);
}
//4.关闭流
in.close();
}
}
public class StreamCopyDemo {
public static void main(String[] args){
//1.创建源(输入)
File resources = new File("H:/xinyi/stream/OutputStrean.txt");
//1.创建目标(输出)
File target = new File("H:/xinyi/stream/OutputStrean_target.txt");
try(
//2.创建输入流对象
InputStream in = new FileInputStream(resources);
//2.创建输出流对象
OutputStream out = new FileOutputStream(target);
){
//3.具体io操作
byte [] buffer = new byte[25];
int len = -1;
//in.read(buffer) 读取多个字节,并且存储到buffer数组中,返回读取字节的个数;如果是-1,说明文件已读完
while ((len = in.read(buffer))!= -1) {
out.write(buffer, 0, len);
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
字符编码转换:
public class EnCodingDemo {
public static void main(String[] args) throws Exception {
String msg = "生活不止眼前的苟且";
byte[] data = msg.getBytes("UTF-8");
String ret = new String(data,"ISO-8859-1");
data = ret.getBytes("ISO-8859-1");
ret = new String(data,"UTF-8");
System.out.println(ret);
}
}