Search code examples
javastringconcatenationstring-concatenation

Java concatenation not working


This code should get the absolute path, append a string from a preferences file and then append ".json" to match the necessary file. I tried using "+" to concatenate strings, but it was giving the same output as the StringBuilder.append()

    StringBuilder pt= new StringBuilder(path);
    pt.append(System.getProperty("file.separator"));
    pt.append("lib");
    pt.append(System.getProperty("file.separator"));
    pt.append("ling");
    pt.append(System.getProperty("file.separator"));
    String lingua =PrefManager.getPref("lingua")+("=");
    System.out.println(lingua);
    pt.append(lingua);
    System.out.println("com extensão"+pt.toString());
    String file = pt.toString();
    System.out.println(file);
    System.out.println(file);
    Object obj = parser.parse(new FileReader(file));

This is my console output:

=t-br
=om extensão/home/mateus/BrinoBuildScript/Filesx64/lib/ling/pt-br
=home/mateus/BrinoBuildScript/Filesx64/lib/ling/pt-br
=home/mateus/BrinoBuildScript/Filesx64/lib/ling/pt-br
java.io.FileNotFoundException: /home/mateus/BrinoBuildScript/Filesx64/lib/ling/p= (No such file or directory)

How can a variable have three different outputs to console? what should I do to fix this?


Solution

  • Mateus. Your console output is printing the last character of the line on the first column. Rendered correctly, your console output should look like this:

    pt-br=
    com extensão\home\mateus\BrinoBuildScript\Filesx64\lib\ling\pt-br=
    \home\mateus\BrinoBuildScript\Filesx64\lib\ling\pt-br=
    \home\mateus\BrinoBuildScript\Filesx64\lib\ling\pt-br=
    

    In this output, you can see that String file is correctly set (although you probably don't intend to have a trailing '=').

    While you are being careful to use the system path separator, the concatenation is a bit clumsy. If you are using an old version of Java, ou may try to compose your path using the File class:

    final String path = "\\home\\mateus\\BrinoBuildScript\\Filesx64";
    final File libFolder = new File(path, "lib");
    final File lingFolder = new File(libFolder, "ling");
    final File languageFolder = new File(lingFolder, PrefManager.getPref("lingua"));
    System.out.println(languageFolder.getAbsolutePath());
    

    If you are using a recent version of Java, you may use the Paths API (which does handle platform-specific path separators):

    final Path p = Paths.get(path, "lib", "ling", PrefManager.getPref("lingua"));
    System.out.println(p);
    

    See the Java tutorial on the Paths API here:

    https://docs.oracle.com/javase/tutorial/essential/io/pathOps.html