下面我有一些方法,基本上我的问题是当我尝试从.txt
文件中读取时。该应用程序在内存中工作正常。当我将decode()
添加到重载的构造函数时,我在Tomcat服务器日志中收到以下错误:
Constructor threw exception; nested exception is java.lang.NumberFormatException: For input string: ""
当我看到更多时,它指向解码方法中的这一行
currentDVD.setDvdId(Integer.parseInt((currentTokens[0])));
但我似乎无法弄清问题是什么。有一次,我能够从文件中读取,然后我试图让编码方法起作用,某些事情发生了。任何帮助将不胜感激。
public class DvdLibraryInFileImpl implements DvdLibraryDao {
private Map<Integer, DVD> dvdMap = new HashMap<>();
public static final String DVD_FILE = "dvd.txt";
public static final String DELIMITER = "::";
private static int dvdIdCounter = 0;
public DvdLibraryInFileImpl() throws FileNotFoundException {
decode();
}
@Override
public DVD addDVD(DVD dvd) {
dvd.setDvdId(dvdIdCounter);
dvdIdCounter++;
dvdMap.put(dvd.getDvdId(), dvd);
return dvd;
}
@Override
public DVD getDVDById(int dvdId) {
return dvdMap.get(dvdId);
}
@Override
public List<DVD> getAllDVDSByName(String searchByName) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public List<DVD> getAllDVDS() {
List<DVD> allDVDS = new ArrayList<>(dvdMap.values());
return allDVDS;
}
@Override
public void updateDVD(DVD dvd) {
dvdMap.put(dvd.getDvdId(), dvd);
}
@Override
public void removeDVD(int dvdId) {
dvdMap.remove(dvdId);
}
@Override
public void decode() throws FileNotFoundException {
Scanner sc = new Scanner(new BufferedReader(new FileReader(DVD_FILE)));
String[] currentTokens;
while (sc.hasNextLine()) {
String currentLine = sc.nextLine();
currentTokens = currentLine.split(DELIMITER);
DVD currentDVD = new DVD();
currentDVD.setDvdId(Integer.parseInt((currentTokens[0])));
currentDVD.setTitle(currentTokens[1]);
currentDVD.setReleaseDate(currentTokens[2]);
currentDVD.setMpaaRating(currentTokens[3]);
currentDVD.setDirectorsName(currentTokens[4]);
currentDVD.setStudio(currentTokens[5]);
currentDVD.setUserRating(currentTokens[6]);
dvdMap.put(Integer.parseInt((currentTokens[0])), currentDVD);
}
}
@Override
public void encode() throws IOException {
PrintWriter out = new PrintWriter(new FileWriter(DVD_FILE));
Set<Integer> keySet = dvdMap.keySet();
for (Integer i : keySet) {
out.print((dvdMap.get(i)).getDvdId());
out.print(DELIMITER);
out.print((dvdMap.get(i)).getTitle());
out.print(DELIMITER);
out.print((dvdMap.get(i)).getReleaseDate());
out.print(DELIMITER);
out.print((dvdMap.get(i)).getMpaaRating());
out.print(DELIMITER);
out.print((dvdMap.get(i)).getDirectorsName());
out.print(DELIMITER);
out.print((dvdMap.get(i)).getStudio());
out.print(DELIMITER);
out.print((dvdMap.get(i)).getUserRating());
out.println("");
}
out.flush();
out.close();
}
}
答案 0 :(得分:0)
问题是因为currentLine
没有收到正确的输入数据(来自用户输入)。
您应该确保currentTokens
设置了正确的DvdId(应该是数字值),否则Integer.parseInt((currentTokens[0]))
行会将NumberFormatException
抛出非数字或空(&#34;& #34;)数据。
您需要使用数字dvdid
确保输入的输入数据正确无误。
例如,输入以下数据: 1234 :: DVDTITLE :: 29-OCT-2016 ::额定值1 ::董事:: STUDIO :: RATING2
我强烈建议您添加输入验证以处理方案,例如输入非数字值或高于最大值的评级或包含数字值的导演名称等等。