英文:
Read multiple path within one single txt file using JAVA
问题
我有几条路径需要从txt格式文件中读入程序。为了简化这个过程,我想将所有的路径/目录存储到一个txt文件中,并为每个路径分配值。
TXT文件:
C:/folder1/data
D:/folder2/excel
E:/folder3/doc
JAVA:
final String Local_dir = System.getenv().get("USERNAME");
String dir = FileUtils.readFileToString(new File("C:/Users/" + Local_dir + "/Desktop/sample_paths.txt"), "UTF-8");
final String Path1 = dir.trim();
final String Path2 = dir.trim();
final String Path3 = dir.trim();
我的问题是,我如何更新上面的代码使其正常工作?
英文:
I have several paths to read into the program from txt format file. In order to simply the process, I would like to stored all the paths/directory into one txt file and assign values to each path.
TXT file:
C:/folder1/data
D:/folder2/excel
E:/folder3/doc
JAVA:
final String Local_dir = System.getenv().get("USERNAME")
String dir = FileUtils.readFileToString(new File("C:/Users/$Local_dir/Desktop/sample_paths.txt"), "UTF-8")
final String Path1 = dir.trim()
final String Path2 = dir.trim()
final String Path3 = dir.trim()
My question is how can I update the above code to make it work?
答案1
得分: 2
你可以从你的计算机中获取主目录,并使用Files.readAllLines方法获取整个内容:
String user = System.getProperty("user.home");
List<String> lines = Files.readAllLines(Paths.get(user, "Desktop", "sample_paths.txt"));
String path1 = lines.get(0);
String path2 = lines.get(1);
String path3 = lines.get(2);
英文:
You can get the home directory from your computer and use the Files.readAllLines method to get the whole content:
String user = System.getProperty("user.home");
List<String> lines = Files.readAllLines(Paths.get(user, "Desktop", "sample_paths.txt"));
String path1 = lines.get(0);
String path2 = lines.get(1);
String path3 = lines.get(2);
答案2
得分: 1
假设您的文件包含回车和换行,并且您的文本文件不包含第一行 TXT file:
,我建议使用以下代码:
final String Local_dir = System.getenv().get("USERNAME");
String dir = FileUtils.readFileToString(new File("C:/Users/" + Local_dir + "/Desktop/sample_paths.txt"), "UTF-8");
String[] lines = dir.split("\r\n");
final String Path1 = lines[0];
final String Path2 = lines[1];
final String Path3 = lines[2];
所以这是一个简单的分割操作来创建这些行。
编辑:我还假设您的前两行代码对您起作用。
英文:
Assuming that your file has carriage return and line feeds, and that your text file does not contain this first line TXT file:
, I would suggest the following code:
final String Local_dir = System.getenv().get("USERNAME")
String dir = FileUtils.readFileToString(new File("C:/Users/$Local_dir/Desktop/sample_paths.txt"), "UTF-8");
String[] lines = dir.split("\r\n");
final String Path1 = lines[0];
final String Path2 = lines[1];
final String Path3 = lines[2];
So it is a simple splitting to create the lines.
Edit: I also assume that your two first lines of code working for you.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论