Created
May 30, 2013 02:57
-
-
Save azenla/5675480 to your computer and use it in GitHub Desktop.
File Adder and Remover
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
| package test; | |
| import java.io.*; | |
| import java.util.ArrayList; | |
| import java.util.Iterator; | |
| public class FileTest { | |
| public static ArrayList<String> original = new ArrayList<String>(); | |
| public static void main(String[] args) throws IOException { | |
| File file = new File("./original.txt"); | |
| if (!file.exists()) { | |
| file.createNewFile(); | |
| } | |
| load(file); | |
| add("example"); | |
| save(file); | |
| } | |
| public static void add(String line) { | |
| original.add(line); | |
| } | |
| public static void remove(String line) { | |
| original.remove(line); | |
| } | |
| public static void save(File file) throws IOException { | |
| BufferedWriter writer = new BufferedWriter(new FileWriter(file)); | |
| Iterator iterator = original.iterator(); | |
| while (iterator.hasNext()) { | |
| String line = (String) iterator.next(); | |
| writer.write(line); | |
| if (iterator.hasNext()) { | |
| writer.newLine(); | |
| } | |
| } | |
| writer.flush(); | |
| writer.close(); | |
| } | |
| public static void load(File file) throws IOException { | |
| BufferedReader reader = new BufferedReader(new FileReader(file)); | |
| String line; | |
| original.clear(); | |
| while ((line = reader.readLine()) != null) { | |
| original.add(line); | |
| } | |
| reader.close(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment