读取文本文件始终返回0 – Java

我正在尝试读取文本文件以获取版本号但由于某种原因,无论我放在文本文件中它总是返回0(零)。

文本文件名为version.txt,它不包含空格或字母,只包含1个字符作为数字。 我需要它来返回那个号码。 关于为什么这不起作用的任何想法?

static int i; public static void main(String[] args) { String strFilePath = "/version.txt"; try { FileInputStream fin = new FileInputStream(strFilePath); DataInputStream din = new DataInputStream(fin); i = din.readInt(); System.out.println("int : " + i); din.close(); } catch(FileNotFoundException fe) { System.out.println("FileNotFoundException : " + fe); } catch(IOException ioe) { System.out.println("IOException : " + ioe); } } private final int VERSION = i; 

这是我在需要读取文本文件时使用的默认解决方案。

 public static ArrayList readData(String fileName) throws Exception { ArrayList data = new ArrayList(); BufferedReader in = new BufferedReader(new FileReader(fileName)); String temp = in.readLine(); while (temp != null) { data.add(temp); temp = in.readLine(); } in.close(); return data; } 

将文件名传递给readData方法。 然后你可以使用for循环来读取arraylist中的唯一一行,并且可以使用相同的循环从不同的文件中读取多行…我的意思是用arraylist做你喜欢的任何事情。

请不要使用DataInputStream

根据链接的Javadoc,它允许应用程序以与机器无关的方式从底层输入流中读取原始Java数据类型。 应用程序使用数据输出流来写入稍后可由数据输入流读取的数据。

您想要读取File (而不是数据输出流中的数据)。

请使用try-with-resources

既然你似乎想要一个ascii整数,我建议你使用一个Scanner

 public static void main(String[] args) { String strFilePath = "/version.txt"; File f = new File(strFilePath); try (Scanner scanner = new Scanner(f)) { int i = scanner.nextInt(); System.out.println(i); } catch (Exception e) { e.printStackTrace(); } } 

使用初始化块

初始化块将被复制到类构造函数中,在您的示例中删除public static void main(String[] args) ,类似于

 private int VERSION = -1; // <-- no more zero! { String strFilePath = "/version.txt"; File f = new File(strFilePath); try (Scanner scanner = new Scanner(f)) { VERSION = scanner.nextInt(); // <-- hope it's a value System.out.println("Version = " + VERSION); } catch (Exception e) { e.printStackTrace(); } } 

将其解压缩为方法

 private final int VERSION = getVersion("/version.txt"); private static final int getVersion(String strFilePath) { File f = new File(strFilePath); try (Scanner scanner = new Scanner(f)) { VERSION = scanner.nextInt(); // <-- hope it's a value System.out.println("Version = " + VERSION); return VERSION; } catch (Exception e) { e.printStackTrace(); } return -1; } 

甚至

 private final int VERSION = getVersion("/version.txt"); private static final int getVersion(String strFilePath) { File f = new File(strFilePath); try (Scanner scanner = new Scanner(f)) { if (scanner.hasNextInt()) { return scanner.nextInt(); } } catch (Exception e) { e.printStackTrace(); } return -1; }