Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.util.Scanner;
- public class FileHelper {
- /**
- * Opens a text file and reads it's contents as a String
- *
- * @param filePath The path to the file to be opened
- */
- public static String openTextFile(String filePath) {
- // You can use the Scanner class to read input from a file
- Scanner scanner;
- // The StringBuilder class is efficient for string concatenation
- StringBuilder sb = new StringBuilder();
- try {
- scanner = new Scanner(new File(filePath));
- while (scanner.hasNextLine()) {
- sb.append(scanner.nextLine() + "\n");
- }
- scanner.close();
- } catch (Exception e) {
- //e.printStackTrace();
- System.out.println("\n\n\nUnable to openTextFile: " + filePath + " - maybe it hasn't been created yet???");
- }
- return sb.toString();
- }
- /**
- * Saves string data to a file on the file system.
- *
- * @param filePath The path to the file to be saved
- * @param fileData The data to put in the file
- */
- public static boolean saveTextFile(String filePath, String fileData){
- try{
- PrintWriter output = new PrintWriter(filePath);
- output.println(fileData);
- output.close();
- return true;
- }catch(Exception e){
- System.out.println("Error: " + e.getMessage());
- return false;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement