0

I would need to write in a local file from a bean.

I have studied:

How do I create a file and write to it in Java?

https://howtodoinjava.com/java-8/java-8-write-to-file-example/

And I have tried the code:

package beans;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;


@Stateless
public class ConviertePuntosNota {

    public String convertidor(int evaluacion) {

        try {

            List<String> lines = Arrays.asList("ConviertePuntosNota::convertidor::el usuario 9ntrodujo: " + evaluacion);
            Path file = Paths.get("log.txt");
            Files.write(file, lines, Charset.forName("UTF-8"));


            return evaluacion >= 5 ? "Apto" : "No apto";
        } catch (IOException ex) {
            Logger.getLogger(ConviertePuntosNota.class.getName()).log(Level.SEVERE, null, ex);
        }
        return "ERROR";
    }
}

We would expect a file called log.txt in the same directoy as the bean is located.

Here wee see that in the hierarchy it does not show up:

enter image description here

Also if we try to search it in the project's directoy it does not appear:

enter image description here

In addition I tried to LOG the absolute path where it is being saved, adding:

Logger.getLogger(ConviertePuntosNota.class.getName()).log(Level.WARNING, null, file.toAbsolutePath().toString());

After Files.write, and we see an empty log:

enter image description here

Also it does not spawns on the hierarchy:

enter image description here

And it is not being found in the project:

enter image description here

Coud you help me please, thank you

Other post I have read before asking this question:

FileIO from an stateless session bean

Yone
  • 2,064
  • 5
  • 25
  • 56
  • A bean is not located in a directory. It is located in a package,on the CLASSPATH. Your expectations don't make sense. – user207421 Mar 18 '18 at 12:58
  • 2
    You will want to read about relative files, and current directories. You have *no guarantee* about the location of log.txt. Generally, it’s best for Java EE code to create files in a temporary directory, using [Files.createTempFile](https://docs.oracle.com/javase/9/docs/api/java/nio/file/Files.html#createTempFile-java.lang.String-java.lang.String-java.nio.file.attribute.FileAttribute...-). – VGR Mar 18 '18 at 14:47
  • Possible duplicate of [Java EE programmers do not write to files](https://stackoverflow.com/questions/1789597/java-ee-programmers-do-not-write-to-files) – contrapost Mar 18 '18 at 19:29

0 Answers0