gpt4 book ai didi

Java 扫描仪文件

转载 作者:行者123 更新时间:2023-11-29 07:57:23 25 4
gpt4 key购买 nike

我有一台扫描仪可以读取 .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;
}
}

最佳答案

因为你把csv文件和源代码放在一起,不能直接new File,你可以试试,

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

关于Java 扫描仪文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16764458/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com