26 Ağustos 2017 Cumartesi

Java - Dosya Okuma / Yazma - Error Handling

Okuma Islemi

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class FileOperations1 {

 public static void main(String[] args) {
  // 1. Define the path that we read the file
  // \ younunu ya / yap ya da \\ kullan. 
  // java bu sekilde anliyor.
  String filename = "C:\\Users\\Gamze\\Java Udemy\\FileToRead.txt";
  String text = null;
  
  // 2. Create the file in Java
  File file = new File(filename);
  
  // 3. Open the file
  BufferedReader br;
  
  // alt satirda exception handling lazim.
  //cunku o isimde bir dosya bulunmayabilir.
  try {
   br = new BufferedReader(new FileReader(file));

   
   // 4. Read the file
   // dosya okunmasi sirasinda txt olamyabilir.
   // ppt veya image olabilir. hata handling lazim
   text = br.readLine();
   
   // 5.Close the resources
   br.close();
   
  } catch (FileNotFoundException e) {
   System.out.println("ERROR:File is not found "+ filename);
   e.printStackTrace();
  } catch (IOException e) {
   System.out.println("ERROR:Could not read the data "+ filename);
   e.printStackTrace();
  } finally {
   System.out.println("Finished reading file");
  }
  System.out.println(text);
  
  
 }

}


Here is the output:
Finished reading file
This is the file for reading purpose.

Yazma Islemi

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;

public class FileOperations1_Write {

 public static void main(String[] args) {
  // 1. Define the path
  String filename = "C:\\Users\\Gamze\\Java Udemy\\FileToWrite.txt";
  String text = "I am writing to this file.";
  
  // 2. Create the file in java
  File file = new File(filename);
  
  // 3. Open file writer
  FileWriter fw;
  try {
   fw = new FileWriter(file);
   // 4. Write to file
   fw.write(text);
   
   // 5. Close the file
   fw.close();
   
  } catch (IOException e) {
   System.out.println("ERROR: Could not read the file " + filename);
   e.printStackTrace();
  } finally {
   System.out.println("Closing the file writer.");
  }
  

 }

}


Bu isimde bir dosya olusturulup icine mesaji yazar.

Hiç yorum yok:

Yorum Gönder