Skip to content

Instantly share code, notes, and snippets.

@naelabdeljawad
Created January 29, 2021 15:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save naelabdeljawad/d1075e2e54a640f560d2c428a7485fde to your computer and use it in GitHub Desktop.
Save naelabdeljawad/d1075e2e54a640f560d2c428a7485fde to your computer and use it in GitHub Desktop.
File Reader
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.util.Scanner;
public class FileReaderUtils {
static StringBuffer stringBufferOfData = new StringBuffer();
static String filename = null;
public static void replacement(StringBuffer stringBufferOfData, String lineToEdit, String replacementText) {
int startIndex = stringBufferOfData.indexOf(lineToEdit);
int endIndex = startIndex + lineToEdit.length();
stringBufferOfData.replace(startIndex, endIndex, replacementText);
}
public static void writeToFile(String data, String filename) {
try {
stringBufferOfData = new StringBuffer(data);
BufferedWriter bufwriter = new BufferedWriter(new FileWriter(filename));
bufwriter.write(stringBufferOfData.toString());
bufwriter.close();
} catch (Exception e) {
System.out.println("Error occured while attempting to write to file: " + e.getMessage());
}
}
public static StringBuffer readFile(String filetoread) throws FileNotFoundException {
filename = filetoread;
Scanner fileToRead = null;
try {
fileToRead = new Scanner(new File(filename));
for (String line; fileToRead.hasNextLine() && (line = fileToRead.nextLine()) != null;) {
System.out.println(line);
stringBufferOfData.append(line).append("\r\n");
}
fileToRead.close();
} catch (Exception e) {
e.printStackTrace();
}
return stringBufferOfData;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment