Skip to content

Instantly share code, notes, and snippets.

@edylle
Created January 4, 2018 17:47
Show Gist options
  • Save edylle/17465ce1403e4a13c039c637d5860641 to your computer and use it in GitHub Desktop.
Save edylle/17465ce1403e4a13c039c637d5860641 to your computer and use it in GitHub Desktop.
Example of a method that create a file and writes texts in it
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class TextFileExample {
public static void main(String[] args) {
BufferedWriter bw = null;
FileWriter fw = null;
List<String> textList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
textList.add("Text " + i);
}
try {
File file = new File("C:\\test");
fw = new FileWriter(file.getAbsoluteFile());
bw = new BufferedWriter(fw);
for (String c : textList) {
if (c != null && !c.isEmpty()) {
bw.write(c);
}
bw.newLine();
}
bw.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bw != null) {
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment