走近Guava(七): 文件操做

文件操做:

  • 複製文件
File original  = new File("path/to/original");
File copy = new File("path/to/copy");
Files.copy(original, copy);
  • 文件移動/重命名
File original = new File("src/main/resources/copy.txt");
File newFile = new File("src/main/resources/newFile.txt");
try{
   Files.move(original, newFile); //移動或重命名文件,相似Unix中的mv
}catch (IOException e){
   e.printStackTrace();
}
  • 將文件讀取爲字符串列表
List<String> readLines = Files.readLines(file, Charsets.UTF_8);
  • 爲文件生成hash值
File file = new File("src/main/resources/sampleTextFileOne.txt");
HashCode hashCode = Files.hash(file, Hashing.md5());
System.out.println(hashCode);
  • 寫或追加文件
File file = new File("quote1.txt");
String hamletQuoteStart = "To be, or not to be";
Files.write(hamletQuoteStart,file, Charsets.UTF_8);//寫文件
         
String hamletQuoteEnd = ",that is the question";
Files.append(hamletQuoteEnd,file,Charsets.UTF_8); //追加文件
         
String overwrite = "Overwriting the file";
Files.write(overwrite, file, Charsets.UTF_8); //重寫文件

ByteSource類

  • ByteSource表明一個可讀的字節源
  • 從文件建立ByteSource
File f1 = new File("quote1.txt");
ByteSource byteSource = Files.asByteSource(f1);
byte[] readBytes = byteSource.read();
System.out.println(readBytes);

ByteSink類

  • ByteSink表明一個可寫的字節源
  • 建立ByteSink
File dest = new File("destfile.txt");
ByteSink byteSink = Files.asByteSink(dest);
File file = new File("srcfile.txt");
byteSink.write(Files.toByteArray(file));
  • 將ByteSource複製到ByteSink
File dest = new File("destfile.txt");
File source = new File("srcfile.txt");
ByteSource byteSource = Files.asByteSource(source);
ByteSink byteSink = Files.asByteSink(dest);
byteSource.copyTo(byteSink);

ByteStreams和CharStreams

  • 限制輸入流大小
ByteStreams.limit(inputStream, 10)
  • 合併CharStreams
@Test
public void joinCharStreamsTest() throws Exception {
	File f1 = new File("file1.txt");
	File f2 = new File("file2.txt");
	File f3 = new File("file3.txt");
	File joinedOutput = new File("file123.txt");

	List<InputSupplier<InputStreamReader>> inputSuppliers = getInputSuppliers(f1, f2, f3);
       InputSupplier<Reader> joinedSupplier = CharStreams.join(inputSuppliers);
	OutputSupplier<OutputStreamWriter> outputSupplier = Files.newWriterSupplier(joinedOutput, Charsets.UTF_8);
	CharStreams.copy(joinedSupplier, outputSupplier);
	String joinedOutputString = joinFiles(joinedOutput);
	System.out.println(joinedOutputString);
}
//將多個文件合併爲字符串
private String joinFiles(File... files) throws IOException {
	StringBuilder builder = new StringBuilder();
	for (File file : files) {
		builder.append(Files.toString(file, Charsets.UTF_8));
	}
	return builder.toString();
}
//將多個文件轉換爲InputSuppler<InputStreamReader>類型的列表
private List<InputSupplier<InputStreamReader>> getInputSuppliers(File... files) {
	List<InputSupplier<InputStreamReader>> list = Lists.newArrayList();
	for (File file : files) {
		list.add(Files.newReaderSupplier(file, Charsets.UTF_8));
	}
	return list;
}

Closer類

  • Closer能夠保證註冊的Closable對象,在Closer關閉時,註冊的Closable對象也會被關閉。
Closer closer = Closer.create();
try {
	File destination = new File("destfile.txt");
	BufferedReader reader = new BufferedReader(new FileReader("srcfile.txt"));
	BufferedWriter writer = new BufferedWriter(new FileWriter(destination));
	closer.register(reader);
	closer.register(writer);
	String line;
	while ((line = reader.readLine()) != null) {
		writer.write(line);
	}
} catch (Throwable t) {
	throw closer.rethrow(t);
} finally {
	closer.close();
}

BaseEncoding類

  • BaseEncoding針對字節碼的編碼工做。
  • 一些用例
@Test
public void encodeDecodeTest() throws Exception {
	File file = new File("srcfile.txt");
	byte[] bytes = Files.toByteArray(file);
	BaseEncoding baseEncoding = BaseEncoding.base64();
	String encoded = baseEncoding.encode(bytes); // 將字節以Base64編碼
}

@Test
public void encodeByteSinkTest() throws Exception {
	File srcFile = new File("srcfile.txt");
	File encodedFile = new File("encodedfile.txt");
	CharSink charSink = Files.asCharSink(encodedFile, Charsets.UTF_8);
	BaseEncoding baseEncoding = BaseEncoding.base64();
	ByteSink byteSink = baseEncoding.encodingSink(charSink); //將charSink轉爲ByteSink
	ByteSource byteSource = Files.asByteSource(srcFile);
	byteSource.copyTo(byteSink); //copy ByteSource to ByteSink
	String encodedBytes = baseEncoding.encode(byteSource.read());
}
以上就是Guava的文件處理。

不吝指正。 java

相關文章
相關標籤/搜索