Passing file path as an argument through a Method in Java
In this Article , I will step through the sample code , and show you how to create a Method to accept File Path as an Argument.
</pre> package tryresources; import java.io.BufferedReader; import java.io.PrintWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class accessFile { // Declare 100 length for array "files" static File[] files = new File[100]; // Declare 100 length for array "bReaders" static BufferedReader[] bReaders= new BufferedReader[100]; // Initial Value For size" static int size =0; // Initial Value For size2" static int size2 =0; // Where the File is located static String desc ="C:/Users/User/Desktop/textFile.txt"; //-----------Reading File ( Method) ------------------------------------------------------- public static void readingFile(String fz) { // Every time the Method is being Call , add one to the Size size = size +1; //then create A New File instance base on the new size files[size] = new File(fz); // Every time the Method is being Call , add one to the Size size2 = size2 +1; //then create A New BufferReeader instance base on the Inputed length try { //Create New BufferedReader Instance " bReaders) bReaders[size2] = new BufferedReader(new FileReader(files[size])); String line; //Create a new new BufferedReader object named br by reading the new instant file while ((line = bReaders[size2].readLine()) != null) { // while bufferReader are able to read some line in the File , Print out the content // in the File System.out.println(line); } } catch (FileNotFoundException e) { System.out.println("Can't find file " + files[size].toString()); } catch (IOException e) { System.out.println("Unable to read file " + files[size].toString()); } finally { // releases all system resources from the streams try { bReaders[size2].close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static void main(String[] args) { // First will Read the File readingFile(desc); // Write Something to the File PrintWriter writer1 =null; try { writer1 = new PrintWriter(new File(desc)); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } writer1.write("I Like Java."); writer1.flush(); writer1.close(); // Read the newly overwrite Value readingFile(desc); } } <pre>
Output
Previous Blog on reading File using Java here
Check Out Java Help Center here
Leave a Reply