gpt4 book ai didi

Java,从文件分配变量

转载 作者:行者123 更新时间:2023-11-30 11:28:50 26 4
gpt4 key购买 nike

我想知道如何创建一个从文件读取并分配变量的 java 程序。

import java.io.*;

public class Reader {
public static void main(String[] args) {
String str;
String time=null;
try {
BufferedReader reader = new BufferedReader(new FileReader("pathfilehere"));
while((a = reader.readLine()) != null) {
reader.readLine();
}
} catch(FileNotFoundException e){System.out.println("Error: "+e.getMessage());
} catch(IOException e){System.out.println("Error: "+e.getMessage());
}
System.out.println(time);
}
}

如果我有一个带有变量“str”的 txt 文件,它的值为“randomstring”,我的问题是如何告诉我的 java 程序从文本文件中分配这个变量并将其存储到 java 程序中以供使用以后呢?

最佳答案

import java.io.*;

public class Reader {
public static void main(String[] args) {

BufferedReader reader = null;
StringBuilder randomstring = new StringBuilder();
try {
reader = new BufferedReader(new FileReader("file.txt"));


String line = reader.readLine();
while(line != null) {
randomstring.append(line + '\n');

line = reader.readLine();
}
} catch(FileNotFoundException e){System.out.println("Error: "+e.getMessage());
} catch(IOException e){System.out.println("Error: "+e.getMessage());
}
finally{
try{
reader.close();
}catch(Exception E){}
}
System.out.println(randomstring.toString());
}
}

关于Java,从文件分配变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18731697/

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