使用Scanner读取文本文件(Java)

huangapple go评论90阅读模式
英文:

Reading Text File WIith Scanner (Java)

问题

  1. import java.util.Scanner;
  2. import java.io.File;
  3. import java.io.FileNotFoundException;
  4. public class Driver {
  5. public static void main(String[] args) {
  6. String fileName = "p1.txt";
  7. Scanner inputStream = null;
  8. System.out.println("The file " + fileName + "\ncontains the following lines: \n");
  9. try
  10. {
  11. inputStream = new Scanner(new File(fileName));
  12. }
  13. catch(FileNotFoundException e)
  14. {
  15. System.out.println("Error opening the file " + fileName);
  16. System.exit(0);
  17. }
  18. while(inputStream.hasNextLine())
  19. {
  20. String line = inputStream.nextLine();
  21. System.out.println(line);
  22. }
  23. inputStream.close();
  24. }
  25. }

"p1.txt"文件中的内容如下:

  1. p, -4, 5
  2. q, 19, 8
  3. r, 3, 0
  4. x, 7.4, -1
  5. y, -2.3, -16.5
  6. z, 0, 1

出于某种原因,我的代码无法读取文本文件,并给出以下输出:

  1. The file p1.txt
  2. contains the following lines:
  3. Error opening the file p1.txt
  4. 我不确定我需要做什么。
英文:

My Text file is called p1 and it contains:

  1. p, -4, 5
  2. q, 19, 8
  3. r, 3, 0
  4. x, 7.4, -1
  5. y, -2.3, -16.5
  6. z, 0, 1

My code is:

  1. import java.util.Scanner;
  2. import java.io.File;
  3. import java.io.FileNotFoundException;
  4. public class Driver {
  5. public static void main(String[] args) {
  6. String fileName = "p1.txt";
  7. Scanner inputStream = null;
  8. System.out.println("The file " + fileName + "\ncontains the following lines: \n");
  9. try
  10. {
  11. inputStream = new Scanner(new File(fileName));
  12. }
  13. catch(FileNotFoundException e)
  14. {
  15. System.out.println("Error opening the file " + fileName);
  16. System.exit(0);
  17. }
  18. while(inputStream.hasNextLine())
  19. {
  20. String line = inputStream.nextLine();
  21. System.out.println(line);
  22. }
  23. inputStream.close();
  24. }
  25. }

For some reason my code can't read my text file and gives me the following output:

  1. The file p1.txt
  2. contains the following lines:
  3. Error opening the file p1.txt

I'm not sure what I need to do.

答案1

得分: 1

这是因为您的文件 "p1.txt" 不存在。请检查文件的位置。它应该放在同一个目录中。

英文:

This is because your file "p1.txt" does not exists. Check the location of your file. It should be placed in same directory.

答案2

得分: 1

确保txt文件与项目在同一个文件夹中,如果不在,请提供路径。

英文:

Make sure that txt file is in the same folder as the project, if not give a path to it.

huangapple
  • 本文由 发表于 2020年9月3日 15:56:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/63719225.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定