java读取src路径下的文件

r囧r小猫 2022-05-27 11:06 411阅读 0赞

在eclipse中建立java工程,如下所示:
这里写图片描述
test.txt是需要我们读取的文件。
下面读取test.txt文件

  1. package com.File;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. /** * 读取src目录下的文件 * @author echo * */
  7. public class Readsrc {
  8. public static void main(String[] args) throws IOException {
  9. // first();
  10. try {
  11. second();
  12. } catch (Exception e) {
  13. e.printStackTrace();
  14. }
  15. }
  16. /** * 第一种,直接得到输入流 * @throws IOException */
  17. public static void first() throws IOException {
  18. InputStream in = Readsrc.class.getClassLoader().getResourceAsStream("test.txt");
  19. byte[] bytes = new byte[1024];
  20. int length;
  21. while((length = in.read(bytes)) != -1) {
  22. System.out.write(bytes, 0, length);
  23. }
  24. }
  25. /** * 第二种,先获取文件的绝对路径 * @throws Exception */
  26. public static void second() throws Exception {
  27. String filePath = Readsrc.class.getResource("/test.txt").getPath();
  28. filePath = filePath.substring(1);
  29. InputStream in = new FileInputStream(new File(filePath));
  30. byte[] bytes = new byte[1024];
  31. int length;
  32. while((length = in.read(bytes)) != -1) {
  33. System.out.write(bytes, 0, length);
  34. }
  35. }
  36. }

发表评论

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

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

相关阅读