×

Java Open File

Java Desktop class give an open() strategy to open a filr. It has a place with a java.awt package. Work area execution is stage subordinate, so it is important to check the working framework upholds Desktop or not.

The Desktop class searches for a related application enrolled on the local work area to deal with a file.

How to open a file in java?

There are following ways of opening a file in Java:

  • Java Desktop class
  • Java FileInputStream class
  • Java BufferedReader class
  • Java FileReader class
  • Java Scanner class
  • Java nio bundle

Java desktop class: Java Desktop class give an open() technique to open a record. It has a place with a java.awt bundle.

Work area execution is stage subordinate, so it is important to check the working framework upholds Desktop or not.

The Desktop class searches for a related application enrolled on the local work area to deal with a record.

In the event that there is no related application or application is neglects to be sent off, it tosses the FileNotFoundException.

  • Dispatches the client default program to show a predefined URI.
  • Dispatches the client default mail client with a discretionary mail-to URI.
  • Dispatches the enrolled application to open, alter, or print a predefined record.
  • The open() strategy for Desktop class dispatches the related application to open a record. It takes a record as a contention.

The mark of the technique is:  public void open (File record) tosses IOException

The technique tosses the accompanying special cases:

  1. NullPointerException: If the record is invalid.
  2. IllegalArgumentException: It is tossed when the record doesn't exist.
  3. IOException: It is tossed when there is no application related with the given record type.
  4. UnsupportedOperationExecution:  If the ongoing stage doesn't uphold the Desktop.Action.Open activity.
//open file example no 1
import java.awt.Desktop;
import java.io.*;
public class FileOpen1
{
public static void main(String[] args)
{
try
{
//constructor of document class having record as contention
File record = new File("C:\\demo1\\demo1file.txt"); //here record is even termed as file
if(!Desktop.isDesktopSupported())//check in the event that Desktop is upheld by Platform or not
{
System.out.println("not upheld");
return;
}
Work area work area = Desktop.getDesktop();
if(file.exists())//checks document exists or not
desktop.open(file);//opens the predetermined document
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

At the point when we run the above program, it opens the predetermined text record in the default content manager. We can likewise open the .docx, .pdf, and .jpg record.

Java FileInputStream class: Java FileInputStream class is utilized to open and peruse a record. We can open and peruse a record by utilizing the constructor of the FileInputStream class.

The mark of the constructor is:

public FileInputStream(File record) throws FileNotFoundException

It acknowledges a record as a contention. It tosses FileNotFoundException on the off chance that the record doesn't exist or document name is a registry.

//open file example 2

import java.io.*;
import java.util.Scanner;
public class FileOpen
{
public static void main(String args[])
{
try
{
//constructor of document class having record as contention
Document file=new File("C:\\demo1\\demo1file.txt");
FileInputStream fis=new FileInputStream(file);//opens an association with a real document
System.out.println("file content: ");
int r=0;
while((r=fis.read())!=-1)
{
System.out.print((char)r);//prints the substance of the document
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

Java BufferedReader class: Java BufferedReader class peruses text from a person input stream. It has a place with a java.io bundle. We utilize the constructor of the BufferedReader class to open or peruse a record.

The mark of the constructor is: public BufferedReader(Reader in)

It makes a buffering character-input stream that utilizes a default? sized input cradle. It utilizes a default size input support.

//open file example no 3

import java.io.*;
import java.util.Scanner;
public class FileOpen3
{
public static void main(String args[])
{
try
{
//constructor of File class having document as contention
Document file=new File("C:\\demo1\\demo1file.txt");
//makes a cushion peruser input stream
BufferedReader br=new BufferedReader(new FileReader(file));
System.out.println("file content: ");
int r=0;
while((r=br.read())!=-1)
{
System.out.print((char)r);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

Java FileReader class: Java FileReader class is likewise utilized for opening and perusing a record. It has a place with a java.io bundle. It is a comfort for perusing characters of the documents. It is utilized for perusing crude bytes utilizing the FileInputStream class. We utilize the constructor of the FileInputStream class to open and peruse a record.

The mark of the constructor is:

public FileReader(File record) tosses FileNotFoundException

It acknowledges a record as a contention. It tosses the FileNotFoundException on the off chance that the predefined record doesn't exist or the document name is a registry.

//open file example no 4:

import java.io.*;
public class FileOpen4
{
public static void main(String args[])
{
try
{
//constructor of the File class having document as a contention
FileReader fr=new FileReader("C:\\demo11\\demo1file.txt");
System.out.println("file content: ");
int r=0;
while((r=fr.read())!=-1)
{
System.out.print((char)r);//prints the substance of the document
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

Java Scanner Class:  Java Scanner class is likewise utilized for opening and perusing a record. The Scanner class has a place with java.util bundle. The constructor of Scanner class is utilized for opening and perusing a document.

 The mark of the constructor is:

public scanner (File source) tosses FileNotFoundException

It acknowledges a record (to be checked) as a contention. It likewise tosses FileNotFoundException, in the event that the wellspring of the record isn't found.

//open file program example 5

import java.io.File;
import java.util.Scanner;
public class FileOpen5
{
public static void main(String[] args)
{
try
{
Record file=new File("C:\\demo1\\demo1file.txt");
Scanner sc = new Scanner(file);//record to be checked
while (sc.hasNextLine())//returns valid if and provided that scanner has another token
System.out.println(sc.nextLine());
}
catch(Exception e)
{
e.printStackTrace();
}
}
 }

Java nio package:  readAllLines() technique: The readAllLines() strategy is the technique for File class.

It peruses all lines from a record and bytes from the document are decoded into characters utilizing UTF-8 charset. It returns the lines from the document as a rundown.

The mark of the strategy is:

public static List<String> readAllLines(Path way) throws IOException

Where way is the record way.

Above technique is identical to summoning the accompanying:

File.readAllLines(path, Standard CharSets.UTF_8)

Collections.emptyList(): The emptyList() technique is the strategy for Collection class which have a place with java.util bundle. Getting an unfilled list is utilized.

 The mark of the technique is:  public static last <T> List <T> emptyList()

//open file example no 6

import java.util.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.io.*;
public class FileOpen6
{
public static List<String> readFileInList(String fileName)
{
List<String> lines = Collections.emptyList();
try
{
lines=Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8);
}
get (IOException e)
{
e.printStackTrace();
}
bring lines back;
}
public static void main(String[] args)
{
List l = readFileInList("C:\\demo1\\demo1file.txt");
Iterator<String> itr = l.iterator();//access the components
while (itr.hasNext())//returns valid if and provided that scanner has another token
System.out.println(itr.next());//prints the substance of the record
}
}

Related Topics

Types of Garbage Collector in Java

Garbage collection is a Java feature that offers automatic memory management. The JVM is in charge of it. The programmer does not have to handle object creation and deallocation. We...

3 minutes read.

Features of Java

The objective of the Java programming language is to provide portability, security, and simplicity. In spite of this, Java has a number of features that makes it a popular language...

5 minutes read.

Java Math signum() Method

The signum() method of Java Math class returns the signum function of the value. Syntax: public static double signum(double d)public static float signum (float d) Parameters: The parameter ‘d’ represents the floating-point value whose...

2 minutes read.

Missing Number in an Arithmetic Progression in Java

Given an array that shows the elements of an orderly arithmetic progression. Find the missing number to complete the succession of elements. Example:  Input: a [ ] = {2 , 4 , 6...

3 minutes read.

Java String length() method

Java String length() method returns length of the characters in a String. Syntax: public int length() Returns It returns length of the characters Java String length() method example 1          public class JavaStringLengthEx1  ...

1 minute read.

Java Get File Size

There are three ways to get the file size in Java. Using Java InputOutput Using NewInputOutput Library Files.size() Method FileChannel.size() Method Using Apache Commons InputOutput Using Java InputOutput: The Java IO package offers the classes that deal...

5 minutes read.

Ad Hoc Problem on Arrays in Java

Ad hoc problems are issues that arise unexpectedly and require immediate attention. These problems can range from small and straightforward issues to more complex and time-consuming problems. Examples of ad...

3 minutes read.

Davis Staircase Problem in Java

Davis has several stairs in his home and prefers to ascend one, two, or three steps at a time. As a highly clever youngster, he thinks about how many ways...

3 minutes read.

Difference between String and Char Array in Java

We are heading to examine some significant differences between String and Character arrays. Both char arrays and String hold the series of characters and are utilised as a cluster of...

3 minutes read.

How to Convert long to int in Java

How to Convert long to int in Java When we assign a larger type value to a variable of smaller type, then we need to perform explicit casting for the conversion....

2 minutes read.

Creating API Document Javadoc tool

The JavaDoc utility is a document generator tool written in Java that generates standard documentation in HTML format. It parses declarations and documentation in a source file collection that describes...

3 minutes read.

How to Convert String to Date in Java

How to Convert String to Date in java You can convert String to Date in Java by using the parse() method. There are two classes which have parse() method namely, DateFormat and SimpleDateFormat classes....

2 minutes read.

Static Array in Java

In this tutorial, we will study static arrays in Java. An array is a data structure that is of great importance in any programming language. It is classified into two...

3 minutes read.

Adapter class in Java

By using the adapter classes, we can implement Listener interfaces. With the help of adapter classes, we can save code as it provides all implementation methods of listener interfaces Advantages of...

3 minutes read.

Java Math with Methods and Examples

Java Math class contains various methods for performing math operations like min(), max(), avg() and various trigonometric functions like sin(), cos(), tan() etc. Methods: The java.lang.Math class contains various methods for performing...

5 minutes read.

Java Read File Line by line

Java provides two options to read files line by line. Each option offers different benefits and has its own set of drawbacks. Following are the ways through which on accomplish...

5 minutes read.

Java 9 Tutorial

The Java 9 is most popular release of java programming to make it platform modular. It is used to improve JDK and java implementation security. It provides JAVA SE and...

3 minutes read.

Session Tracking in Java

When a series of requests from the same User (i.e., requests coming from the same browser) occurs over an extended period of time, servlets employ a mechanism known as session...

3 minutes read.

Java Math tanh() Method

The tanh() method of Java Math class returns the hyperbolic tangent of the specified double value. Syntax: public static double tanh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic tangent is to...

2 minutes read.

Java Naming Conventions

JAVA NAMING CONVENTIONS Java naming convention is a standard pattern for writing your identifier name such as class, interfaces, methods, constants, variable, etc. These patterns are not standard rules that you must...

2 minutes read.