有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java从主机读取文件

我试图从与源代码位于同一文件夹的计算机读取一个文件,当我运行代码时,代码会说:文件不存在 你能帮我吗

import java.io.*;
import java.util.*;
public class Lotto1 {
  static String[][] arr;
  static String name, number;
  public static void main(String[] args) throws IOException {
    File f = new File("D:\\Filipe\\Project Final\\src\\database_lotto.txt.txt");
    Scanner s;
    try {
      s = new Scanner(f);
      BufferedReader reader = new BufferedReader(new FileReader(f));
      int lines = 0;
      while(reader.readLine() != null) {
        lines++;
      }
      reader.close();
      arr = new String[lines][3];
      int count = 0;
      //while theres still another line
      while(s.hasNextLine()) {
        arr[count][0] = s.next() + "" + s.next();
        arr[count][1] = s.next();
        arr[count][2] = s.next();
        count++;
      }
    } catch(FileNotFoundException ex) {
      System.out.println("File does not exist");
    }

共 (2) 个答案

  1. # 1 楼答案

    我已经推断出您要做什么并重新编码,但是如果文件在您所说的位置,这个实现将读取该文件

    public static void main(String[] args) {
        final String filename = "database_lotto.txt";
        final File lottoFile = new File(filename);
    
        try (final Scanner scanner = new Scanner(lottoFile)) {
            final List<String[]> storage = new ArrayList<String[]>();
            while (scanner.hasNextLine()) {
                storage.add(scanner.nextLine().split(" "));
            }
        }catch (FileNotFoundException ex) {
            System.out.println("File not found :(");
        }
    }
    
  2. # 2 楼答案

    您在Unix/Linux机器上吗

    最好使用文件。分隔符而不是\,因为文件。separator使用系统字符作为目录(\on Win、/on Linux等)

    使用文件。exists()来检查文件是否存在,然后再使用它