[英]Java - Reading in signed integers from a file
我試圖從一個文件中讀取10個有符號整數到一個數組,由於某種原因,它沒有發生,我沒有在編譯和運行時得到任何錯誤。 我只是想要第二雙眼睛看看這個,看看我可能會缺少什么。
測試文件是“input.txt”並包含:-1,4,32,0,-12,2,30,1,-3,-32
這是我的代碼:
public void readFromFile(String filename)
{
try {
File f = new File(filename);
Scanner scan = new Scanner(f);
String nextLine;
int[] testAry = new int[10];
int i = 0;
while (scan.hasNextInt())
{
testAry[i] = scan.nextInt();
i++;
}
}
catch (FileNotFoundException fnf)
{
System.out.println(fnf.getMessage());
}
}
您使用Scanner對象上的默認分隔符。
嘗試使用我在行中使用的分隔符useDelimiter(\\\\ s *,\\\\ s *“)。它的正則表達式用逗號分隔文件中的輸入。
try {
File f = new File("input.txt");
Scanner scan = new Scanner(f);
scan.useDelimiter("\\s*,\\s*");
String nextLine; //left it in even tho you are not using it
int[] testAry = new int[10];
int i = 0;
while (scan.hasNextInt()) {
testAry[i] = scan.nextInt();
System.out.println(testAry[i]);
i++;
}
} catch (FileNotFoundException fnf) {
System.out.println(fnf.getMessage());
}
你可能會拋出另一個你沒有捕獲的異常
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html#nextInt ()
從輸入掃描的int拋出:
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed
或者你可以去舊學校並使用緩沖讀卡器來驗證你是否正在獲取數據
try{
FileInputStream fstream = new FileInputStream(filename);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
System.out.println (strLine);
}
in.close();
}catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.