-1

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?

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
Elif Y
  • 251
  • 1
  • 4
  • 21

2 Answers2

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);
flaxel
  • 4,173
  • 4
  • 17
  • 30
1

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.

jmizv
  • 1,172
  • 2
  • 11
  • 28