Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is the best way to create file and write to it in Java [closed]

Tags:

java

I normally use PrintWritter object to create and write to a file, but not sure if its the best in terms of speed and security compare to other ways of creating and writing to a file using other approaches i.e.

Writer writer = new BufferedWriter(
             new OutputStreamWriter(
             new FileOutputStream("example.html"), "utf-8"));   
writer.write("Something");

vs

File file = new File("example.html");
BufferedWriter output = new BufferedWriter(new FileWriter(file));          
output.write("Something");

vs

File file = new File("example.html");
FileOutputStream is = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(is);    
Writer w = new BufferedWriter(osw);
w.write("something");

vs

PrintWritter pw = new PrintWriter("example.html", "UTF-8");
pw.write("Something");

Also, when to use one over the other; a use case scenario would be appreciated. I'm not asking for how to create and write to file, I know how to do that. Its more of compare and contrast sort of question I'm asking.

like image 978
Simple-Solution Avatar asked Oct 15 '14 10:10

Simple-Solution


3 Answers

I prefer:

boolean append = true;
boolean autoFlush = true;
String charset = "UTF-8";
String filePath = "C:/foo.txt";

File file = new File(filePath);
if(!file.getParentFile().exists()) file.getParentFile().mkdirs();
FileOutputStream fos = new FileOutputStream(file, append);
OutputStreamWriter osw = new OutputStreamWriter(fos, charset);
BufferedWriter bw = new BufferedWriter(osw);
PrintWriter pw = new PrintWriter(bw, autoFlush);
pw.write("Some File Contents");

which gives you:

  1. Decide whether to append to the text file or overwrite it.
  2. Decide whether to make it auto-flush or not.
  3. Specify the charset.
  4. Make it buffered, which improves the streaming performance.
  5. Convenient methods (such as println() and its overloaded ones).
like image 79
Eng.Fouad Avatar answered Oct 19 '22 23:10

Eng.Fouad


Honestly, I don't know if this is the best option, but I think that is a System like, common accepted abstraction:

In.java:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class In {

    public In() {
    }

    /**
     * Tranforms the content of a file (i.e: "origin.txt") in a String
     * 
     * @param fileName: Name of the file to read
     * @return String which represents the content of the file
     */
    public String readFile(String fileName) {

        FileReader fr = null;
        try {
            fr = new FileReader(fileName);
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }

        BufferedReader bf = new BufferedReader(fr);

        String file = "", aux = "";
        try {
            while ((file = bf.readLine()) != null) {
                aux = aux + file + "\n";
            }
            bf.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return aux;
    }
}

Out.java:

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class Out {

    public Out() {}

    /**
     * Writes on the file named as the first parameter the String which gets as second parameter.
     * 
     * @param fileName: Destiny file
     * @param message: String to write on the destiny file
     */
    public void writeStringOnFile(String fileName, String message) {
        FileWriter w = null;
        try {
            w = new FileWriter(fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        BufferedWriter bw = new BufferedWriter(w);
        PrintWriter wr = new PrintWriter(bw);

        try {
            wr.write(message);
            wr.close();
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

IO.java:

public class IO {

    public Out out;
    public In in;

    /**
     * Object which provides an equivalent use to Java 'System' class
     */
    public IO() {
        this.setIn(new In());
        this.setOut(new Out());
    }

    public void setIn(In in) {
        this.in = in;
    }

    public In getIn() {
        return this.in;
    }

    public void setOut(Out out) {
        this.out = out;
    }

    public Out getOut() {
        return this.out;
    }
}

Therefore, you can use the class IO almost in the same way you will use System.

Hope it helps.

Clemencio Morales Lucas.

like image 35
Clemencio Morales Lucas Avatar answered Oct 20 '22 00:10

Clemencio Morales Lucas


The best solution, as usual, depends on your task: either you work with text or with binary data. In the first case you should prefer writers, in the second - streams.

You ask for comparison of approaches to write TEXT into files.

The last case in your question is the best one for writing/creation new text files. It is suitable for 99% of practical tasks.

PrintWritter pw = new PrintWriter("example.html", "UTF-8");
pw.write("Something");

It is short and readable. It supports explicit encoding and buffering. It does not require unnecessary wrappers.

Other old-fashion approaches can and should be used in those cases, where this solution is not applicable. E.g. you want to append any text to file. In this case you have no choice except to use writers based on stream wrappers (unfortunately, FileWriter doesn't support explicit encoding).

like image 23
ursa Avatar answered Oct 20 '22 00:10

ursa