com.github.kaisle.util.FileUtil Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of DotA2-Wrapper Show documentation
Show all versions of DotA2-Wrapper Show documentation
A wrapper for the DotA2 WebAPI written in Java.
package com.github.kaisle.util;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
/**
* Created by Anders Borum on 03-06-2015.
*/
public class FileUtil {
/**
* Get the index of the first line in the file that contains the specified string.
* @param file The file to search through.
* @param searchString The string to search for.
* @return The index of the line if the string is present in the file contents, or -1 if not.
*/
public static int findLine(File file, String searchString) {
try {
List lines = FileUtils.readLines(file);
for (int i = 0; i < lines.size(); i++) {
if (lines.get(i).contains(searchString)) {
return i;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return -1;
}
/**
* Append a line to a file.
* @param file
* @param content
*/
public static void appendLine(File file, String content) {
try {
List lines = FileUtils.readLines(file);
lines.add(content);
FileUtils.writeLines(file, lines);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Append a line to a file.
* @param file
* @param content
*/
public static void appendLinesToMiddle(File file, List content, int lineNumber) {
try {
List lines = FileUtils.readLines(file);
for (int i = 0; i < content.size(); i++) {
lines.add(lineNumber + i, content.get(i));
}
FileUtils.writeLines(file, lines);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Replace a line in a file.
* @param file The file to write to.
* @param lineContent The content to write.
* @param lineNumber The line number.
*/
public static void modifyLine(File file, String lineContent, int lineNumber) {
try {
List lines = FileUtils.readLines(file);
lines.set(lineNumber, lineContent);
FileUtils.writeLines(file, lines);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Get the current workign directory.
* @return
*/
public static String getWorkingDirectory() {
return System.getProperty("user.dir");
}
public static void ensureFileExists (String directory, String fileName) {
try {
if (!FileUtils.directoryContains(new File(directory), new File(fileName))) {
new File(directory + "/" + fileName).createNewFile();
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Remove lines in the file that contain a given string.
* @param file
* @param content
*/
public static void removeLines(File file, String content) {
try {
List lines = FileUtils.readLines(file);
Iterator linesIterator = lines.iterator();
while (linesIterator.hasNext()) {
String line = linesIterator.next();
if (line.contains(content)) {
linesIterator.remove();
}
}
FileUtils.writeLines(file, lines);
} catch (IOException e) {
e.printStackTrace();
}
}
}