java中如何使用相对文件路径读取文件?

lokaqttq  于 2022-12-21  发布在  Java
关注(0)|答案(1)|浏览(124)

文件路径不起作用,input1.txt与library.java位于同一目录中。我应该怎么做来纠正它?我应该如何给予路径,以便它读取文本文件?

package SimpleLibrarySystem;
import java.time.LocalDateTime;
import java.util.*;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
public class Library
{
ArrayList <Book> var = new ArrayList<Book>();
HashMap<Book, LocalDateTime> var1 = new HashMap<Book, LocalDateTime>();
public Library(String person, LocalDateTime time)
{
 try{
    File myfile = new File("input1.txt") ;
    Scanner br = new Scanner(myfile);
    String line = br.nextLine();

    while ((line != null))
    {

        String a = line;
        line = br.nextLine();
        String b = line;
        Book a1 = new Book(a,b,person);
        Book a2 = new Book (a,b, "");
        var.add(a2);
        var1.put(a1,time);
        //System.out.println(a + " "+ b);
        line = br.nextLine();
    }
    br.close();
    }
    catch (Exception e) 
    {
        System.out.println("not working");
    }
}
}
yvgpqqbh

yvgpqqbh1#

代码:

public class Main{

    public static void main(String[] args) {
            int counter = 0;

            try (FileReader fileReader = new FileReader("src/file.txt"); Scanner sc = new Scanner(fileReader)) {
                while (sc.hasNextLine()) {
                    ++counter;
                    sc.nextLine();
                }
            } catch (Exception e) {
                throw new IllegalStateException(e.getMessage());
            }
        System.out.println(counter);
        }
}

检出:how to read file in Java

相关问题