Skip to content

Instantly share code, notes, and snippets.

@hirokazumiyaji
Last active June 26, 2017 14:06
Show Gist options
  • Save hirokazumiyaji/4eebaa81e7bcada6f0978166e0da6545 to your computer and use it in GitHub Desktop.
Save hirokazumiyaji/4eebaa81e7bcada6f0978166e0da6545 to your computer and use it in GitHub Desktop.
package divide;
public class Divider {
private final String inputFilePath;
private final String outputFileDirectory;
private final Map<String, FileWriter> outputWriters = new HashMap<>();
public Divider(String inputFilePath, String outputFileDirectory) {
this.inputfilePath = inputFilePath;
this.outputFileDirectory = outputFileDirectory;
}
public void divide() throws IOException {
try {
try(BufferedReader reader = new BufferedReader(new File(inputFilePath)) {
reader.lines().forEach(line -> {
String[] elements = line.split("\t");
if (elements.length != 2) {
return;
}
try {
FileWriter writer = outputWriters.get(elements[0]);
if (writer == null) {
writer = new FileWriter(new File(outputFileDirectory, elements[0] + ".tsv"));
outputWriters.put(elements[0], writer);
}
writer.write(line + "\n");
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
}
} catch (UncheckedIOException e) {
throw e.getCause();
} finally {
try {
outputWriters.entrySet().forEach(o -> {
try {
o.close();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
} catch (UncheckedIOException e) {
throw e.getCause();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment