1.獲取資源文件或者獲取文本文件等,可以通過Spring的Resource的方式獲取
2.僅有File對象即可獲取正文數據
3.僅有InputStream即可獲取正文數據
1 package com.sxd.test.test1; 2 3 import java.io.BufferedReader; 4 import java.io.File; 5 import java.io.FileReader; 6 import java.io.IOException; 7 import java.io.InputStream; 8 import java.nio.file.Files; 9 import java.util.List; 10 11 import org.junit.Test; 12 import org.springframework.core.io.ClassPathResource; 13 import org.springframework.core.io.Resource; 14 15 public class GetResource { 16 17 /** 18 * 獲取資源文件的 方法之一-----使用Spring架包中的Resource類實現 19 * 當然 獲取資源文件還有不同來源的資源文件有相應的Resource實現: 20 * FileSystemResource-----文件資源 21 * ClassPathResource-----ClassPath資源 22 * UrlResource-----------URL資源 23 * InputStreamResource---InputStream資源 24 * ByteArrayResource-----Byte數組資源 25 * @throws IOException 26 */ 27 @Test 28 public void getResouce() throws IOException{ 29 Resource resource =new ClassPathResource("beanFactoryTest.xml"); 30 InputStream in = resource.getInputStream(); 31 String fileName = resource.getFilename(); 32 String description = resource.getDescription(); 33 long contentLength = resource.contentLength(); 34 File file = resource.getFile(); 35 36 37 System.out.println("文件名:"+fileName); 38 System.out.println("描述:"+description); 39 System.out.println("正文長度:"+contentLength); 40 41 42 /** 43 * 有File對象就可以讀取到正文的數據-----方法1 44 */ 45 List<String> list = Files.readAllLines(file.toPath()); 46 for (String string : list) { 47 System.out.println(string); 48 } 49 50 51 System.out.println("------------------------------------------------------------------------------------------------- "); 52 /** 53 * 有File對象可以讀取正文的數據 ----方法2 54 */ 55 BufferedReader br = new BufferedReader(new FileReader(file)); 56 String str = null; 57 while((str=br.readLine()) != null){ 58 System.out.println(str); 59 } 60 61 System.out.println("--------------------------------------------------------------------------------------------------"); 62 /** 63 * 有InputStream可以讀取正文數據 64 */ 65 int contentLen = in.available(); 66 byte[] st = new byte[contentLen]; 67 in.read(st); 68 System.out.println(new String(st)); 69 70 } 71 }
