English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In most cases, if you try to write content to a file using classes from the java.io package, the file will be overwritten, that is, the existing data in the file will be deleted and new data will be added to it.
However, in some cases, such as logging exceptions to a file (without using a logging framework), you need to append data (messages) to the next line of the file.
You can use the Files class in the java.nio package to perform this operation. This class provides a method namedwrite()
, which method accepts
An object of the Path class, representing a file.
Save the data to the file as a byte array.
You can pass a variable parameter of type OpenOption (interface) as the value to one of the elements of the StandardOpenOption enumeration, which contains10options, namely APPEND, CREATE, CREATE_NEW, DELETE_ON_CLOSE, DSYNC, READ, SPARSE, SYNC, TRUNCATE_EXISTING, WRITE.
You can call this method by passing the file path, the byte array containing the data to be appended, and the option StandardOpenOption.APPEND.
The following Java program has an array that stores5An integer value, we allow the user to select two elements (the index of the elements) from the array and perform division between them. We wrap this code in a try block with three catch blocks that catch ArithmeticException, InputMismatchException, and ArrayIndexOutOfBoundsException. Each of us is calling thewriteToFile()
method.
This method accepts an exception object and uses the Files classwrite()The method attaches it to the file.
public class LoggingToFile { private static void writeToFile(Exception e) throws IOException { //Retrieve the log file Path logFile = Paths.get("ExceptionLog.txt"); //Prepare the data to be recorded byte bytes[] = ("\r\n"+LocalDateTime.now()+": \+e.toString()).getBytes(); //Attach the exception to the file Files.write(logFile, bytes, StandardOpenOption.APPEND); System.out.println("Exception logged to your file"); } public static void main(String [] args) throws IOException { Scanner sc = new Scanner(System.in); int[] arr = {10, 20, 30, 2, 0, 8}; System.out.println("Array: \+Arrays.toString(arr)); System.out.println("Choose numerator and denominator (not 0) from this array (enter positions 0 to 5})"); try { int a = sc.nextInt(); int b = sc.nextInt(); int result = (arr[a])/(arr[b]); System.out.println("Result of \+arr[a]+\/\+arr[b]+": \+result); catch(ArrayIndexOutOfBoundsException ex) { System.out.println("Warning: You have chosen a position which is not in the array"); writeLogToFile(ex); }catch(ArithmeticException ex) { System.out.println("Warning: You cannot divide an number with 0"); writeLogToFile(ex); }catch(InputMismatchException ex) { System.out.println("Warning: You have entered invalid input"); writeLogToFile(ex); } } }
Enter 3 integer values one by one: Array: [10, 20, 30, 2, 0, 8] Choose numerator and denominator (not 0) from this array (enter positions 0 to 5) 2 4 Warning: You cannot divide an number with 0 Exception logged to your file
Enter 3 integer values one by one: Array: [10, 20, 30, 2, 0, 8] Choose numerator and denominator (not 0) from this array (enter positions 0 to 5) 5 12 Warning: You have chosen a position which is not in the array Exception logged to your file
Enter 3 integer values one by one: Array: [10, 20, 30, 2, 0, 8] Choose numerator and denominator (not 0) from this array (enter positions 0 to 5) hello Warning: You have entered invalid input Exception logged to your file
2019-07-19T17:57:09.735: java.lang.ArithmeticException: / by zero 2019-07-19T17:57:39.025: java.lang.ArrayIndexOutOfBoundsException: 12 2019-07-19T18:00:23.374: java.util.InputMismatchException