简体   繁体   中英

Write text file doesnt work java

This is my project architecture:

Architecture Project

I want to write on the file "file.txt", I tried with BufferedWriter and PrintWriter but it doesnt work without error.

My code with BufferedWriter :

ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("FileTLV.txt").getFile());
    try{

        BufferedWriter writer = new BufferedWriter(new FileWriter(file));
        writer.write("I want to write a String");
        writer.close();

    }catch (IOException e) {
        e.printStackTrace();
    }

And my code with PrintWriter:

    ClassLoader classLoader = getClass().getClassLoader();
    File file = new File(classLoader.getResource("FileTLV.txt").getFile());
    try{

        PrintWriter writer = new PrintWriter(new FileWriter(file));
        writer.print("I want to print a String");
        writer.flush();
        writer.close();

    }catch (IOException e) {
        e.printStackTrace();
    }

The code execute without any error.

Application resources are read-only. You cannot write to them.

If you want to override your application resource, write the content to a new location (such as a temporary file or a location somewhere under the user's home directory), and write some code that checks for that file before falling back on your built-in application resource.

Also, the getFile() method of URL does not convert a URL to a valid file name. It returns the path and query portions of the URL, with all percent-escapes intact, so if you are running from a directory or .jar whose full path contains any characters which are not allowed in URLs, the result will not be usable. The method should be avoided. (The method name comes from the fact that java.net.URL was a class present in Java 1.0, and when Java 1.0 was released, most URLs did in fact refer to physical files.)

Just use Files .write from java.nio (Java 7+)

here's an example:

List<String> lines = Arrays.asList("line1", "line2");
Path file = Paths.get("filename.txt");
Files.write(file, lines, Charset.forName("UTF-8"));

And what's really nice:

"The method ensures that the file is closed when all bytes have been written (or an I/O error or other runtime exception is thrown)."

Files.write(filePathObj, content, StandardOpenOption.APPEND);

allows you to append to a file (take a look at the different OpenOptions )

In general, Files.nio is really useful, also for reading

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM