Java(springboot) 讀取txt文本內容代碼實例


這篇文章主要介紹了Java(springboot) 讀取txt文本內容代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

代碼如下

public class TxtTest {
  private static final Logger logger = LoggerFactory.getLogger(TxtTest.class);
  public static String readTxt(File file) throws IOException {
    String s = "";
    InputStreamReader in = new InputStreamReader(new FileInputStream(file),"UTF-8");
    BufferedReader br = new BufferedReader(in);
    StringBuffer content = new StringBuffer();
    while ((s=br.readLine())!=null){
      content = content.append(s);
    }
    return content.toString();
  }
 
  public static void main(String[] args) {
    try {
        //通過絕對路徑獲取文件
      String s1 = TxtTest.readTxt(new File("C:\\Users\\....\\du.txt"));
      logger.info(s1);
 
        //spring boot中文件直接放在resources目錄下
      String s2 = TxtTest.readTxt(ResourceUtils.getFile("classpath:du.txt"));
      logger.info(s2);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

 以上代碼如果部署在linux服務器上,就找不到SpringBoot項目resources根目錄下的du.txt文件。所以需要修改成如下方式:

import com.huixiaoer.joy.api.common.config.EnvConfig;
import com.huixiaoer.joy.api.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import java.io.*;


@Slf4j
@Service
public class FileServiceImpl implements FileService {

    @Override
    public String readTxtFile() {
        try {
            byte[] bytes;

            ClassPathResource classPathResource = new ClassPathResource("file/du.txt");
            //獲取文件流
            InputStream keyStream = classPathResource.getInputStream();
            bytes = IOUtils.toByteArray(keyStream);
            keyStream.read(bytes);
            keyStream.close();

            ByteArrayInputStream certBis = new ByteArrayInputStream(bytes);
            InputStreamReader input = new InputStreamReader(certBis);
            BufferedReader bf = new BufferedReader(input);
            String line = null;
            StringBuilder sb = new StringBuilder();
            while((line=bf.readLine()) != null){
                sb.append(line);
            }

            return sb.toString();
        } catch (IOException e) {
            log.error("讀取文件錯誤",e);
        }
        return "";
    }

}

 

轉載於:https://www.jb51.net/article/180411.htm


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM