🚀 feat(新增): OutputStream和输入流使用

This commit is contained in:
bunny 2024-07-31 15:56:57 +08:00
parent f7e2150735
commit f38bffe06a
6 changed files with 248 additions and 0 deletions

View File

@ -0,0 +1,4 @@
package cn.bunny;
public class FileTest {
}

View File

@ -0,0 +1,78 @@
package cn.bunny.http;
import lombok.SneakyThrows;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
public class HttpClientTest {
// 同步发送HTTP请求
private static void sendSyncRequest(HttpClient httpClient, String URL) throws Exception {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI(URL))
.GET()
.build();
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Response status code: " + response.statusCode());
System.out.println("Response body: " + response.body());
System.out.println("Response header: " + response.headers());
}
// 异步发送HTTP请求
private static void sendAsyncRequest(HttpClient httpClient, String URL) {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(URL))
.GET()
.build();
CompletableFuture<HttpResponse<String>> future = httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString());
future.thenAccept(response -> {
System.out.println("Async Response status code: " + response.statusCode());
System.out.println("Async Response body: " + response.body());
}).join(); // 等待异步请求完成
}
// 设置重定向策略
private static void setRedirectPolicy(HttpClient httpClient) {
// 设置自动重定向策略
HttpClient.Redirect newClient = httpClient.followRedirects();
// 使用newClient继续发送请求
}
// 设置自定义执行器
private static void setExecutor(HttpClient httpClient) {
// 设置自定义执行器
Optional<Executor> newClient = httpClient.executor(); // 可以传入自定义的Executor
// 使用newClient继续发送请求
}
@SneakyThrows
public static void main(String[] args) {
String URL = "https://www.itxst.com/sortablejs/neuinffi.html";
// 创建HttpClient对象
HttpClient httpClient = HttpClient.newHttpClient();
// 同步发送HTTP请求
sendSyncRequest(httpClient, URL);
// 异步发送HTTP请求
sendAsyncRequest(httpClient, URL);
// 设置重定向策略
setRedirectPolicy(httpClient);
// 设置自定义执行器
setExecutor(httpClient);
httpClient.close();
}
}

View File

@ -0,0 +1,17 @@
package cn.bunny.http;
import lombok.SneakyThrows;
import org.junit.jupiter.api.Test;
import java.net.URI;
import java.net.http.HttpRequest;
public class HttpRequestTest {
@SneakyThrows
@Test
void requestTest() {
String URL = "https://www.itxst.com/sortablejs/neuinffi.html";
HttpRequest httpRequestGet = HttpRequest.newBuilder().uri(new URI(URL)).GET().build();
HttpRequest httpRequestPost = HttpRequest.newBuilder().uri(new URI(URL)).POST(HttpRequest.BodyPublishers.ofString("json")).build();
}
}

View File

@ -0,0 +1,96 @@
package cn.bunny.path;
import lombok.SneakyThrows;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class PathTest {
// 关闭流的正确方式
// 在Java中使用流Stream操作后应该使用try-with-resources语句来确保流资源被正确关闭而不是直接调用close()方法
// 另外Stream<Path>并不是实现AutoCloseable接口的因此不能直接调用close()方法关闭应该通过使用try-with-resources或者使用forEach方法内部自动关闭流
@SneakyThrows
@Test
void pathTest1() {
Path listPath = Path.of("D:/MyFolder/文档和软件");
// 输出这个目录下所有文件文件夹
try (Stream<Path> list = Files.list(listPath)) {
list.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
// 循环遍历这个目录下所有文件
try (Stream<Path> walk = Files.walk(Path.of("D:/MyFolder/文档和软件/图片"))) {
walk.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
// 创建路径对象
@Test
void pathsTest() {
// 创建一个表示当前工作目录的Path对象
Path currentPath = Paths.get("");
System.out.println("Current Path: " + currentPath);
// 创建一个表示绝对路径的Path对象
Path absolutePath = Paths.get("C:/Users/username/Documents");
System.out.println("Absolute Path: " + absolutePath);
// 创建一个表示相对路径的Path对象
Path relativePath = Paths.get("src/main/java/com/example");
System.out.println("Relative Path: " + relativePath);
// 创建一个带有多个路径组件的Path对象
Path nestedPath = Paths.get("C:/", "Users", "username", "Documents", "JavaProjects");
System.out.println("Nested Path: " + nestedPath);
}
@Test
void pathTest() {
Path path = Path.of("D:\\MyFolder\\文档和软件");
// resolve(String other)方法用于将当前路径解析为另一个路径它接受一个字符串参数other可以是相对路径或者绝对路径示例中将当前路径与subfolder/file.txt组合返回一个新的Path对象resolvedPath表示完整的路径D:\MyFolder\文档和软件\subfolder\file.txt
Path resolvedPath = path.resolve("subfolder/file.txt");
// D:\MyFolder\文档和软件\subfolder\file.txt
System.out.println(resolvedPath);
// `resolveSibling(String other)`方法与`resolve()`类似但是它是相对于当前路径的父路径进行解析的示例中将当前路径的父路径与`anotherFolder`组合返回一个新的`Path`对象`resolvedSiblingPath`表示路径`D:\MyFolder\anotherFolder`
Path siblingResolvedPath = path.resolveSibling("anotherFolder");
System.out.println(siblingResolvedPath);
// `relativize(Path other)`方法用于计算两个路径之间的相对路径示例中假设`otherPath`表示另一个路径`D:\MyFolder\文档和软件\subfolder\file.txt``relativePath`表示从`path``otherPath`的相对路径`subfolder\file.txt`
Path siblingResolvedPath2 = path.resolveSibling("anotherFolder");
System.out.println(siblingResolvedPath2);
// relativize(Path other)方法用于计算两个路径之间的相对路径示例中假设otherPath表示另一个路径D:\MyFolder\文档和软件\subfolder\file.txt则relativePath表示从path到otherPath的相对路径subfolder\file.txt
Path otherPath = Path.of("D:\\MyFolder\\文档和软件\\subfolder\\file.txt");
Path relativePath = path.relativize(otherPath);
System.out.println(relativePath);
// normalize()方法用于标准化路径它消除路径中的冗余部分例如.当前目录..上级目录示例中normalizedPath将返回一个标准化后的路径对象即D:\MyFolder\文档和软件
Path absolutePath = path.toAbsolutePath();
System.out.println("absolutePath" + absolutePath);
// getParent()方法返回当前路径的父路径示例中如果path是D:\MyFolder\文档和软件则parentPath会返回D:\MyFolder
Path parentPath = path.getParent();
System.out.println(parentPath);
// getRoot()方法返回当前路径的根路径部分对于D:\MyFolder\文档和软件rootPath将返回D:\作为根路径
Path rootPath = path.getRoot();
System.out.println(rootPath);
// toFile()方法将Path对象转换为对应的java.io.File对象这在需要与旧版Java API或需要使用File对象的库中特别有用
File file = path.toFile();
System.out.println(file);
}
}

View File

@ -0,0 +1,41 @@
package cn.bunny.stream;
import lombok.SneakyThrows;
import org.junit.jupiter.api.Test;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Arrays;
public class InputStreamTest {
@SneakyThrows
@Test
void testInputStream() {
InputStream inputStream = new FileInputStream("D:\\MyFolder\\文档和软件\\图片.zip");
// read()方法从输入流中读取下一个字节并返回读取的字节数据以整数形式如果已到达流的末尾则返回 -1这个方法通常用于逐字节地读取数据
int read = inputStream.read();
System.out.println(read);
// 读取所有字节
byte[] bytes = inputStream.readAllBytes();
System.out.println(Arrays.toString(bytes));
// 处理每个字节的数据
int byteRead;
while ((byteRead = inputStream.read()) != -1) {
System.out.println(byteRead);
}
// skip(long n)方法跳过并丢弃输入流中的 n 个字节数据并返回实际跳过的字节数这对于跳过文件中一些特定字节的数据很有用
long bytesSkipped = inputStream.skip(10);
System.out.println(bytesSkipped);
// available()方法返回当前可从输入流中读取的字节数这个方法通常用于检查流中是否还有未读取的数据
int bytesAvailable = inputStream.available();
System.out.println(bytesAvailable);
// close()方法关闭输入流并释放与之关联的任何系统资源在使用完输入流后调用此方法是非常重要的以避免资源泄漏和系统资源的浪费
inputStream.close();
}
}

View File

@ -0,0 +1,12 @@
package cn.bunny.stream;
import lombok.SneakyThrows;
import org.junit.jupiter.api.Test;
public class OutputStreamTest {
@SneakyThrows
@Test
void testOutputStream() {
}
}