java读取本地文件与非本地文件内容

骑猪看日落 2023-06-06 07:50 40阅读 0赞
  1. private String readFile ( String path ) throws IOException {
  2. StringBuilder builder = new StringBuilder();
  3. InputStreamReader reader = null;
  4. BufferedReader bfReader = null;
  5. try {
  6. if (path.contains("http://")) {
  7. URL url = new URL(path);
  8. InputStream is = url.openStream();
  9. reader = new InputStreamReader(is,"utf-8");
  10. bfReader = new BufferedReader(reader);
  11. } else {
  12. reader = new InputStreamReader( new FileInputStream( path ), "UTF-8" );
  13. bfReader = new BufferedReader( reader );
  14. }
  15. String tmpContent = null;
  16. while ( ( tmpContent = bfReader.readLine() ) != null ) {
  17. builder.append( tmpContent );
  18. }
  19. bfReader.close();
  20. } catch ( UnsupportedEncodingException e ) {
  21. // 忽略
  22. }
  23. return this.filter( builder.toString() );
  24. }
  25. // 过滤输入字符串, 剔除多行注释以及替换掉反斜杠
  26. private String filter ( String input ) {
  27. return input.replaceAll( "/\\*[\\s\\S]*?\\*/", "" );
  28. }

发表评论

表情:
评论列表 (有 0 条评论,40人围观)

还没有评论,来说两句吧...

相关阅读

    相关 py读取本地文件

    在Python中,可以使用内置的`open()`函数来读取本地文件。以下是一个基本的示例,演示如何打开并读取一个文本文件: 使用 'r' 参数表示我们想要读取文件