IO
注意:当输入流和输出流的地址是同一个,需要先确保完全读完内容再进行输出,不然会导致覆盖掉尚未读取的内容,最佳做法是将文件读取和写入操作分开,并且最好写入到一个新的文件中,最后再替换原文件。
输入和输出主要由Read和writer
read()从此输入流中读取下一个字节的数据。值字节作为 int 在 0 到 255 范围内返回。如果因为已到达流的末尾而没有可用字节,则返回值 -1
read(byte[] b)将数据读取到byte数组中,读入缓冲区的字节总数,如果因为已到达流的末尾而没有更多数据,则为 -1。
read(byte[] b, int off, int len)从此输入流中读取最多 len 字节的数据到byte字节数组中。如果 len 不为零,则该方法会阻塞,直到某些输入可用;否则,不读取任何字节并返回 0。
write(int b)
将指定字节写入此文件输出流。
write(byte[] b)将指定字节数组中的 b.length 个字节写入此文件输出流。
write(byte[] b, int off, int len)从偏移量 off 开始的指定字节数组中将 len 字节写入此文件输出流。
available() 返回输入流读取预估的字节数
I/O流
//创建字节输入流
OutputStream fos =new FileOutputStream(dest+"\\"+"copy_"+file.getName());
字节输入流FileInputStream
public static void in() {
InputStream is = null;
try {
is = new FileInputStream("D:/test.txt");
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
int len = 0;
while (true) {
byte[] buffer = new byte[1024];
try {
if (((len = is.read(buffer)) == -1)) {
break;
}
System.out.println(new String(buffer, 0, len));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
FileInputStream fis = new FileInputStream("D:\\test.txt");
循环读取文件,read方法返回读取的字节数,一个一个字节去读取内容,如果返回-1表示文件已经读取完毕
int i = fis.read();
//一次读取一个buf大小的字节
byte[] buf = new byte[1024];
int i = fis.read(buf);
//只读取有效字节数
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
//关闭流
in = new FileInputStream("C:\\Users\\h'j'g\\Desktop\\必背单词.txt");
这里省略了读取和写入操作
//放在最后,输入流使用了就关闭
if (in != null) in.close();
//available() 是Java中某些输入流类提供的方法,用于返回可以从此输入流中无阻塞读取的估计字节数。
字节输出流FileOutputStream
//一次写入一个字节
out.write();
//一次读取buf长度的字节
public static void out(){
try {
OutputStream os = new FileOutputStream("D:/test.txt");
os.write("早上好".getBytes());
os.flush();
os.close();
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
//构造函数的第二个参数设置为true,表示将以追加模式打开文件。这意味着新的内容将被添加到文件的末尾,而不会覆盖现有的内容。
public static void out(){
try {
OutputStream os = new FileOutputStream("D:/test.txt",true);
os.write("早上好".getBytes());
os.flush();
os.close();
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
字符流InputStreamReader/OutputStreamWriter
字符流接收一个字节流作为参数
//字符输入流
public static void in1(){
Reader reader = null;
try {
reader = new InputStreamReader(new FileInputStream("D:/test.txt"),"UTF-8");
int len = 0;
while (true) {
char[] buffer = new char[1024];
if ((len = reader.read(buffer)) == -1) {
break;
}
System.out.println(new String(buffer, 0, len));
}
}catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}finally {
try {
reader.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
//字符输出流
public static void out1(){
Writer writer = null;
try {
writer = new OutputStreamWriter(new FileOutputStream("D:/test.txt",true),"UTF-8");
writer.write(",洛阳");
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}finally {
try {
writer.flush();
writer.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
便捷字符流FileWriter/FileReader
Java提供了FileWriter和FileReader简化字符流的读写,new FileWriter等同于new OutputStreamWriter(new FileOutputStream(file, true))
//便捷字符输出流
public static void out3() {
FileWriter writer = null;
try {
writer = new FileWriter("D:/test.txt",true);
writer.write(",晚上好");
} catch (IOException e) {
throw new RuntimeException(e);
}finally {
try {
writer.flush();
writer.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
//便捷字符输入流
public static void in3() {
FileReader reader = null;
try {
reader = new FileReader("D:/test.txt");
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
int len = 0;
while (true){
char[] buffer = new char[1024];
try {
if (((len = reader.read(buffer)) == -1)){
break;
}
System.out.println(new String(buffer, 0, len));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
try {
reader.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
缓冲流BufferedReader/BufferedWriter
1.接收一个字符流作为参数,readLine()一次读取一行,自带缓冲区
2.除了 readLine() 方法外,BufferedReader 还有 read() 方法,它可以读取单个字符,返回其 ASCII 值。当达到文件末尾时,返回 -1。
3.readChars(char[] cbuf) 方法可以读取一系列字符并存储到一个字符数组中。此方法返回实际读取的字符数,当达到文件末尾时,返回 -1。
public static void main(String[] args) throws IOException{
//创建字节输入流
InputStream in = new FileInputStream("D:\\test.txt");
//创建字符输入流
InputStreamReader isr = new InputStreamReader(in, "UTF-8");
//创建缓冲区
BufferedReader br = new BufferedReader(isr);
//这里参数可以是字符输出流OutputStreamWrite也可以是FileWriter
BufferedWriter bw = new BufferedWriter(new FileWriter("D:\\test.txt"));
while(true){
//读取一行
String line = br.readLine();
if(line == null){
break;
}
bw.write(line);
System.out.println(line);
}
br.close();
isr.close();
in.close();
bw.close();
}
//也可以这样用
public static void main(String[] args) {
String filePath = "example.txt"; // 文件路径
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
对象流ObjectOutputStream/ObjectInputStream
1.想要将对象传输到某处,需要将对象序列化,实现Serializable.
2.跨设备传输对象需要客户端和服务端环境一样,包括目录结构,文件名,包名都要一样
3.如果出现了序列化uid不一样,需要在对象类加个属性serialVersionUID
private static final long serialVersionUID = 1L;
//客户端
public static void main(String[] args) {
//建立连接
try {
Socket socket = new Socket("192.168.119.148",8080);
//通过socket获得输出流
OutputStream oos = socket.getOutputStream();
//创建对象输出流
ObjectOutputStream oo = new ObjectOutputStream(oos);
//创建对象
Student student = new Student("张三",18,1001);
oo.writeObject(student);
oo.flush();
oo.close();
oos.close();
socket.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
//服务端
public static void main(String[] args) {
//建立连接
try {
ServerSocket serverSocket = new ServerSocket(8080);
//监听器
Socket socket = serverSocket.accept();
//获得通道
InputStream ins = socket.getInputStream();
ObjectInputStream out = new ObjectInputStream(ins);
Student s1 = (Student) out.readObject();
System.out.println(s1.getName());
System.out.println(s1.getAge());
System.out.println(s1.getId());
out.close();
ins.close();
socket.close();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
Student s1 = new Student("张三", 20, 1001);
// 序列化,把对象转换成字节数组,输出到文件
//创建对象输出流,参数是字节输出流,两种构造方法,无参和传入字节输出流
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\student.txt"));
//反序列化,从文件中读取字节数组,转换成对象
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:\\student.txt"));
//写入对象
oos.writeObject(s1);
//读取对象
Student s = (Student) ois.readObject();
System.out.println(s.getName());
System.out.println(s.getAge());
System.out.println(s.getId());
ois.close();
//关闭流
oos.close();
文件File
File.renameTo和Files.move
renameTo 方法返回一个布尔值,表示操作是否成功。如果返回 true,则表示文件重命名成功;如果返回 false,则表示重命名失败
Files.move可以实现文件的重命名或移动到不同的位置。Files.move 提供了一种安全的方式来移动文件,因为它保证了操作的原子性(要么完成,要么不执行任何更改)。
如果你需要跨文件系统移动文件,或者需要更可靠的重命名操作,建议使用 java.nio.file.Files.move 方法
//renameTo
public static void main(String[] args) {
File sourceFile = new File("source.txt");
File targetFile = new File("target.txt");
if (sourceFile.renameTo(targetFile)) {
System.out.println("文件重命名成功!");
} else {
System.out.println("文件重命名失败!");
}
}
//Files.move
public static void main(String[] args) {
//这里也能直接定义字符串,后面使用Files.move时当参数传入即可
Path sourcePath = Paths.get("source.txt");
Path targetPath = Paths.get("target.txt");
try {
Files.move(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
System.out.println("文件已成功移动。");
} catch (Exception e) {
System.err.println("移动文件时发生错误: " + e.getMessage());
e.printStackTrace();
}
}
//sourcePath: 要移动的文件或目录的路径。
//targetPath: 移动到的目标位置的路径。
//StandardCopyOption.REPLACE_EXISTING: 如果目标位置已经存在一个文件或目录,这个选项将会覆盖现有的文件或目录。如果没有这个选项,如果目标位置已经有相同名称的文件或目录,Files.move 会抛出 FileAlreadyExistsException。
public static void main(String[] args) {
//创建文件对象,把要操作的文件转换成Java中的File对象
File file = new File("C:\\Users\\h'j'g\\Desktop\\必背单词.txt");
//判断文件是否存在
Boolean isExists = file.exists();
System.out.println(isExists);
//判断文件是否是文件.isFile();
System.out.println(file.isFile());
//判断文件是否是目录.isDirectory();
System.out.println(file.isDirectory());
//获取文件相对路径.getPath();
System.out.println(file.getPath());
//获取绝对路径.getAbsolutePath();
System.out.println(file.getAbsolutePath());
//获取文件名.getName();
System.out.println(file.getName());
//删除文件.delete();
System.out.println(file.delete());
//创建文件.createNewFile();
try {
file.createNewFile();
System.out.println("创建文件成功");
}catch (IOException e){
throw new RuntimeException("创建文件失败");
//e.printStackTrace();
}
//获取文件大小.length();
System.out.println(file.length());
}