English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Come aggiungere dati a un file in Java

In molti casi, se tenti di scrivere contenuti in un file utilizzando le classi del pacchetto java.io, il file verrà sovrascritto, ossia, eliminare i dati esistenti nel file e aggiungere nuovi dati.

Ma in alcuni casi, come registrare eccezioni in un file (senza utilizzare il framework di registrazione), devi aggiungere dati (messaggi) alla riga successiva del file.

Puoi eseguire questa operazione utilizzando la classe Files del pacchetto java.nio. Questa classe fornisce un metodo chiamatowrite()}accetta

  • L'oggetto della classe Path rappresenta un file.

  • Salva i dati in un array di byte nel file.

  • Puoi passare un valore di variabile di tipo OpenOption (interfaccia) come uno degli elementi dell'enumerazione StandardOpenOption, che contiene 10 opzioni, ovvero APPEND, CREATE, CREATE_NEW, DELETE_ON_CLOSE, DSYNC, READ, SPARSE, SYNC, TRUNCATE_EXISTING, WRITE .

Puoi chiamare questo metodo passando il percorso del file, un array di byte contenente i dati da aggiungere e l'opzione StandardOpenOption.APPEND.

esempio

Il seguente programma Java ha un array che memorizza 5 valori interi, facciamo scegliere all'utente due elementi (l'indice degli elementi) e dividere tra loro. Abbiamo avvolto questo codice in un blocco try, che contiene tre catch per ArithmeticException, InputMismatchException e ArrayIndexOutOfBoundsException. Ogni uno di loro chiama ilwriteToFile()metodo.

Questo metodo accetta oggetti eccezionali e utilizza la classe Fileswrite()}Il metodo lo aggiunge al file.

public class LoggingToFile {
   private static void writeToFile(Exception e) throws IOException {
      //Ricerca del file di log
      Path logFile = Paths.get("ExceptionLog.txt");
      //Prepara i dati da registrare
      byte bytes[] = ("\r\n" + LocalDateTime.now() + ": " + e.toString()).getBytes();
      //Aggiungi l'eccezione al file
      Files.write(logFile, bytes, StandardOpenOption.APPEND);
      System.out.println("Eccezione registrata nel 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("Scegli il numeratore e il denominatore (non 0) da questo array (inserisci posizioni 0 a 5)");
      try {
         int a = sc.nextInt();
         int b = sc.nextInt();
         int result = (arr[a]) / (arr[b]);
         System.out.println("Risultato di " + arr[a] + "/" + arr[b] + ": " + result);
      }catch(ArrayIndexOutOfBoundsException ex) {
         System.out.println("Attenzione: hai scelto una posizione che non è nell'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);
      }
   }
}

Output 1

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

Output 2

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

Output 3

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

ExceptionLog.txt

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