0

How would I be able to automatically direct BufferReader Path to the desktop even in different computer.. '''BufferedReader in = new BufferedReader(new FileReader("C:\Users\.....\ ".txt"));''

2 Answers2

0

You can use

  public static void main(String[] args) throws IOException {
    String path = System.getProperty("user.home") + "/Desktop/test.txt";
    BufferedReader in = new BufferedReader(new FileReader(path));
    String line;
    while ((line = in.readLine()) != null) {
      System.out.println("line = " + line);

    }
    in.close();
  }

To get the desktop path and read the text file from it

Falah H. Abbas
  • 512
  • 5
  • 11
0

Here’s how I get the desktop directory:

  • In Windows, I look at the DESKTOP registry entry in HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders.
  • In Linux, I scan the plain text file $XFG_CONFIG_HOME/user-dirs.dirs for a shell-like definition of the XDG_DESKTOP_DIR variable.
  • On other systems, or if the above fails, fall back on the Desktop directory in the user’s home directory.

My implementation looks like this:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;

import java.util.regex.Pattern;

public class DesktopDirectoryLocator {
    public static Path getDesktopDirectory()
    throws IOException,
           InterruptedException {

        String os = System.getProperty("os.name");
        if (os.contains("Windows")) {
            String dir = null;

            ProcessBuilder builder = new ProcessBuilder("reg.exe", "query",
                "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer"
                + "\\Shell Folders", "/v", "DESKTOP");
            builder.redirectError(ProcessBuilder.Redirect.INHERIT);
            Process regQuery = builder.start();
            try (BufferedReader outputReader = new BufferedReader(
                new InputStreamReader(regQuery.getInputStream()))) {

                String line;
                while ((line = outputReader.readLine()) != null) {
                    if (dir == null) {
                        String replaced =
                            line.replaceFirst("^\\s*DESKTOP\\s+REG_SZ\\s+", "");
                        if (!replaced.equals(line)) {
                            dir = replaced.trim();
                        }
                    }
                }
            }

            int exitCode = regQuery.waitFor();
            if (exitCode != 0) {
                throw new IOException(
                    "Command " + builder.command() + " returned " + exitCode);
            }

            if (dir != null) {
                return Paths.get(dir);
            }
        } else if (os.contains("Linux")) {
            // Reference:
            // https://www.freedesktop.org/wiki/Software/xdg-user-dirs/
            // https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html

            Path configDir;
            String configHome = System.getenv("XDG_CONFIG_HOME");
            if (configHome != null) {
                configDir = Paths.get(configHome);
            } else {
                configDir = Paths.get(
                    System.getProperty("user.home"), ".config");
            }

            Path userDirsFile = configDir.resolve("user-dirs.dirs");
            if (Files.isRegularFile(userDirsFile)) {
                try (BufferedReader userDirs =
                    Files.newBufferedReader(userDirsFile)) {

                    String line;
                    while ((line = userDirs.readLine()) != null) {
                        if (line.trim().startsWith("XDG_DESKTOP_DIR=")) {
                            String value =
                                line.substring(line.indexOf('=') + 1);
                            if (value.startsWith("\"") &&
                                value.endsWith("\"")) {

                                value = value.substring(1, value.length() - 1);
                            }

                            Pattern varPattern = Pattern.compile(
                                "\\$(\\{[^}]+\\}|[a-zA-Z0-9_]+)");
                            value = varPattern.matcher(value).replaceAll(r -> {
                                String varName = r.group(1);
                                if (varName.startsWith("{")) {
                                    varName = varName.substring(1,
                                        varName.length() - 1);
                                }
                                String varValue = System.getenv(varName);
                                return (varValue != null ?
                                    varValue : r.group());
                            });

                            return Paths.get(value);
                        }
                    }
                }
            }
        }

        return Paths.get(System.getProperty("user.home"), "Desktop");
    }

    public static void main(String[] args)
    throws IOException,
           InterruptedException {
        System.out.println(getDesktopDirectory());
    }
}

To read a file in that directory, you would use:

Path desktopDir = getDesktopDirectory();
Path file = desktopDir.resolve("example.txt");
try (BufferedReader reader = Files.newBufferedReader(file,
    Charset.defaultCharset())) {

    // ... 
}
VGR
  • 40,506
  • 4
  • 48
  • 63