Java扫描程序文件

时间:2013-05-26 22:59:32

标签: java intellij-idea java.util.scanner

我有一台扫描仪可以读取.csv文件 该文件位于同一目录和.java文件中,但它似乎无法找到该文件 我该怎么做才能解决这个问题?

Scanner scanner = new Scanner(new File("database.csv"));

编辑:抱歉忘了提到我需要使用Scanner软件包,因为在下一行中我使用了分隔符。

Scanner scanner = new Scanner(new File("database.csv"));
scanner.useDelimiter(",|\r|\n");

我也在使用IntelliJIDEA

所以这是完整的代码

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.*;

public class City
{
public String name; // The name of the city
public String cont; // The continent of the city
public int relTime; // Time relative to Hobart (eg. -14 for New York)
public boolean dst; // Does the city use DST?
public boolean valid; // Does the city exist?
Date currDate;

City(){}; // Default constructor
City(String name, String cont, int relTime)
{
    this.name = name;
    this.cont = cont;
    this.relTime = relTime;
    valid = verify();

    if(valid)
    {
        currDate = new Date(System.currentTimeMillis() + (3600000 * relTime));
    }
}

City(String name, String cont, int relTime, int dstStartDay, int dstEndDay)
{
    this.name = name;
    this.cont = cont;
    this.relTime = relTime;
    valid = verify();

    if(valid)
    {
        currDate = new Date(System.currentTimeMillis() + (3600000 * relTime));
        // Is DST in effect?
        if(currDate.after(new Date(currDate.getYear(), 3, dstStartDay, 2, 0)) &&
                currDate.before(new Date(currDate.getYear(), 11, dstEndDay, 2, 0)))
        {
            // It is... so
            relTime--;
        }
    }
}

private boolean verify()
{
    valid = false;

    try
    {
        Scanner scanner = new Scanner(new File("\\src\\database.csv"));
        scanner.useDelimiter(",|\r|\n");
        while(scanner.hasNext())
        {
            String curr = scanner.next();
            String next = new String();
            if(scanner.hasNext())
                next = scanner.next();
            if(curr.contains(cont) && next.contains(name))
                return true;
        }
        scanner.close();
    }
    catch(FileNotFoundException e)
    {
        e.printStackTrace();
    }

    return false;
}
}

4 个答案:

答案 0 :(得分:3)

当你把csv文件与源代码放在一起时,你不能直接使用新文件,你可以试试,

    InputStream resourceAsStream = this.getClass().getResourceAsStream("database.csv");
    Scanner scanner = new Scanner(resourceAsStream);
    scanner.useDelimiter(",|\r|\n");

答案 1 :(得分:2)

创建或读取相对文件时,路径相对于指定的user.dir。在eclipse中,这通常是项目的根源。

您可以按如下方式打印user.dir

System.out.println(System.getProperty("user.dir"));

这是程序正在寻找database.csv文件的地方。将文件添加到此目录或使用绝对路径。

答案 2 :(得分:0)

从项目的根文件夹开始添加文件的完整路径。

例如。

Test是Eclipse中的项目名称。所以我应该写

File csvFile = new File("src\\database.csv");

答案 3 :(得分:0)

您不应该将文件保留在同样包含类文件的目录中。如果这样做,则不应将它们作为文件访问,而应作为资源访问它们,并且应将它们复制到包含已编译的.jar文件的文件夹或.class。如果该文件仅由.jar中的一个类使用,那么您应该使用this.getClass().getResource("database.csv");

缺点是你不能资源。如果你想这样做,我强烈建议不要使用源文件夹作为数据库文件。而是使用系统内的可配置位置(例如当前工作文件夹)。

相关问题