Java: Input Output File

From OnnoWiki
Jump to navigation Jump to search

Sumber: http://www.vogella.de/articles/JavaIO/article.html

Tutorial berikut menjelaskan bagaimana cara membaca (read) dan menulis (write) file menggunakan Java.


I/O (Input / Output) handling for file

Java memberikan cara yang standrad untuk membaca (reading) dan menulis (writing) ke file. Java package "java.io" berisi class yang dapat digunakan untuk membaca dan menulis ke file atau sumber lainnya.

Java IO is handled by several class of the "java.io" package. These classes are usually "chained", e.g. some classes handle the reading and writing of a stream of data while others provide a higher level of abstraction, e.g. to read a line of a file. In general the classes in this package can be divided into the following classes:

   Connection Streams: Represents connections to destinations and sources such as files or network sockets. Usually low-level.
   Chain Streams: Work only if chained to other stream. Usually higher level protocol, for example they provide the functionality to read a full line of a text file.

Reading and writing files

Create a new Java project "de.vogella.java.io" in Eclipse . The following class "MyFile" contains methods for reading and writing a text file.

package de.vogella.java.io;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class MyFile {

	public String readTextFile(String fileName) {
		String returnValue = "";
		FileReader file;
		String line = "";
		try {
			file = new FileReader(fileName);
			BufferedReader reader = new BufferedReader(file);
			while ((line = reader.readLine()) != null) {
				returnValue += line + "\n";
			}
		} catch (FileNotFoundException e) {
			throw new RuntimeException("File not found");
		} catch (IOException e) {
			throw new RuntimeException("IO Error occured");
		}
		return returnValue;

	}

	public void writeTextFile(String fileName, String s) {
		FileWriter output;
		try {
			output = new FileWriter(fileName);
			BufferedWriter writer = new BufferedWriter(output);
			writer.write(s);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}


To test these methods, create a file "Testing.txt" with some text content in your project folder. Create the following class "Main.java" and run it.


package de.vogella.java.io;

public class Main {
	public static void main(String[] args) {
		MyFile myFile = new MyFile();
		String input = myFile.readTextFile("Testing.txt");
		System.out.println(input);
		myFile.writeTextFile("Testing2.txt", input);
	}
} 


Reading resources out of your project / jar

Frequently you need to read resources out of your project or your jar file. You can use the method chain .getClass().getResourceAsStream() from any object to do this.



Referensi

Pranala Menarik