Created
June 9, 2013 18:59
-
-
Save timpulver/5744740 to your computer and use it in GitHub Desktop.
[Processing] Appends text to the end of a text file without rewriting the whole text
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.io.BufferedWriter; | |
| import java.io.FileWriter; | |
| String outFilename = "out.txt"; | |
| void setup(){ | |
| // Write some text to the file | |
| for(int i=0; i<10; i++){ | |
| appendTextToFile(outFilename, "Text " + i); | |
| } | |
| } | |
| /** | |
| * Appends text to the end of a text file located in the data directory, | |
| * creates the file if it does not exist. | |
| * Can be used for big files with lots of rows, | |
| * existing lines will not be rewritten | |
| */ | |
| void appendTextToFile(String filename, String text){ | |
| File f = new File(dataPath(filename)); | |
| if(!f.exists()){ | |
| createFile(f); | |
| } | |
| try { | |
| PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(f, true))); | |
| out.println(text); | |
| out.close(); | |
| } catch (IOException e) { | |
| e.printStackTrace(); | |
| } | |
| } | |
| /** | |
| * Creates a new file including all subfolders | |
| */ | |
| void createFile(File f){ | |
| File parentDir = f.getParentFile(); | |
| try{ | |
| parentDir.mkdirs(); | |
| f.createNewFile(); | |
| }catch(Exception e){ | |
| e.printStackTrace(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment