Search code examples
htmlfileprocesssendvala

Vala How send result file.read to html


i was wondering if anyone could give me pointers on how to send result from action glib.file.read to html.

example i want read file string.txt

File file = File.new_for_path ("string.txt");
try {
    FileInputStream @is = file.read ();
    DataInputStream dis = new DataInputStream (@is);
    string line;

    while ((line = dis.read_line ()) != null) {
        stdout.printf ("%s\n", line);
    }
} catch (Error e) {
    stdout.printf ("Error: %s\n", e.message);
}

return 0;

and i want post result from this proses to file html, example index.html

help would be much appreciated. thanks


Solution

  • here is a short example of how to write data to a file taken from the GNOME Wiki (where you'll find more infos)

    // an output file in the current working directory
    var file = File.new_for_path ("index.html");
    
    // creating a file and a DataOutputStream to the file
    var dos = new DataOutputStream (file.create
        (FileCreateFlags.REPLACE_DESTINATION));
    
    // writing a short string to the stream
    dos.put_string ("this is the first line\n");
    

    so you have to create your output file and create a DataOutputStream to it, and then, change your loop to write the data of your "string.txt" to "index.html". In the end, it would look like this :

    public static int main (string[] args) {
        File in_file = File.new_for_path ("string.txt");
        File out_file = File.new_for_path ("index.html");
    
        // delete the output file if it already exists (won't work otherwise if
        // it does)
        if (out_file.query_exists ()) {
            try {
                out_file.delete ();
            } catch (Error e) {
            stdout.printf ("Error: %s\n", e.message);
            }
        }
    
        try {
            // create your data input and output streams
            DataInputStream dis = new DataInputStream (in_file.read ());
            DataOutputStream dos = new DataOutputStream (out_file.create
                (FileCreateFlags.REPLACE_DESTINATION));
    
            string line;
    
            // write the data from string.txt to index.html line per line
            while ((line = dis.read_line ()) != null) {
                // you need to add a linebreak ("\n")
                dos.put_string (line+"\n");
            }
        } catch (Error e) {
            stdout.printf ("Error: %s\n", e.message);
        }
        return 0;
    }