我对我下面的代码片段有疑问。我有一个名为FILNAVN的文件,它是程序所需信息所在的文件。所述文件的第一行是一行整数,我只需要读一次。这些代码是否真的会这样做?我问,因为我还没有在while循环中编写代码,我实际上也需要一些关于如何执行此操作的提示:P
try{
Scanner leseFraFila= new Scanner(new File(FILNAVN)).useDelimiter(";");
int maaned=leseFraFila.nextInt();
int aar=leseFraFila.nextInt();
int totalFortjeneste=leseFraFila.nextInt();
int totaltAntallMaaneder=leseFraFila.nextInt();
int maanedsleieVanligHybel=leseFraFila.nextInt();
int maanedsleieToppHybel=leseFraFila.nextInt();
while(FILNAVN.hasNext()){
//Here is where I will probably use:
//String linje=leseFraFila.nextLine()
//linje.split(";");
//String .... =
//int ....=
}
}catch(IOException e){
System.out.print(e);
}
答案 0 :(得分:0)
以下是您问题的简短解决方案:
static String readFile(String path, Charset encoding) throws IOException
{
byte[] encoded = Files.readAllBytes(Paths.get(path));
return encoding.decode(ByteBuffer.wrap(encoded)).toString();
}
您现在要做的就是将信息输入字符串:
String readContent = readFile("test.txt", StandardCharsets.UTF_8);
或者您可以使用defaultCharset()。