package org.springblade.mdm.utils; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.springblade.core.tool.api.R; import org.springblade.core.tool.utils.Charsets; import java.io.*; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; public class FileContentUtilTest { //@Test public void testInsert() throws IOException { int lineNo= 0; ByteArrayInputStream byteStream; ByteArrayInputStream streamForCharset; try (InputStream ins = new FileInputStream("D:/a.txt");){ byte[] allBytes = ins.readAllBytes(); byteStream = new ByteArrayInputStream(allBytes); streamForCharset = new ByteArrayInputStream(allBytes); } String charsetName = FileContentUtil.detectFromInputStream(streamForCharset); Charset charset = Charsets.charset(charsetName);//new String("test文本".getBytes(charset)) InputStream newStream = FileContentUtil.insertLine(byteStream,1,"tes中间行t"); try (BufferedReader reader = new BufferedReader(new InputStreamReader(newStream, charset));) { String line; //读取 while((line = reader.readLine()) != null){ lineNo++; System.out.println("line "+lineNo+":"+line); } } catch (IOException e) { throw new RuntimeException(e); } } //@Test public void testDelete() throws IOException { String charsetName = FileContentUtil.detectFromInputStream(new FileInputStream("D:/a.txt")); System.out.println(charsetName); Charset charset = Charsets.charset(charsetName); //System.out.println(charset); } //@Test public void testReadLineAt() throws IOException { Path source = Paths.get("src/test/resources/filecontenttest.txt"); int lineIndex = 1; FileInputStream fis = new FileInputStream(source.toFile()); String expected = "第二行"; String read = FileContentUtil.readLineAt(fis,lineIndex); Assertions.assertEquals(expected,read); } //@Test public void testReplaceReadLineAt(@TempDir Path tempDir) throws IOException { // 加载资源文件 Path source = Paths.get("src/test/resources/filecontenttest.txt"); //File file = new File(classLoader.getResource("filecontenttest.txt").getFile()); File testFile = source.toFile(); try(FileInputStream fis = new FileInputStream(testFile);) { String expected = "newline2"; int lineIndex = 1; InputStream ins = FileContentUtil.replaceAtLine(fis, lineIndex, expected); List list = IOUtils.readLines(ins, Charsets.UTF_8); System.out.println(list); Assertions.assertEquals(expected, list.get(lineIndex)); } } }