Skip to content

Instantly share code, notes, and snippets.

@azenla
Created May 30, 2013 02:57
Show Gist options
  • Select an option

  • Save azenla/5675480 to your computer and use it in GitHub Desktop.

Select an option

Save azenla/5675480 to your computer and use it in GitHub Desktop.
File Adder and Remover
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