×

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

Enterprise Java Beans

One of the many Java APIs for the common development of corporate software is Enterprise Java Beans (EJB). An EJB, a server-side software component, contains the business logic of an...

4 minutes read.

String Matches in Java

Firstly we have to know something about String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java...

3 minutes read.

Byte to Hex in Java

Java exclusively uses byte data types to store in a byte array, which is an array. Each component of a byte array has a default value of 0. Hex String -...

3 minutes read.

Java Byte intValue() method

The intValue()  method of Java Integer class returns an int value for this Integer.  Syntax public int intValue()  Parameters NA  Specified by This method is specified by intValue in class Number  Return Value This method returns the numeric...

1 minute 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.

ConcurrentSkipListSet in Java

ConcurrentSkipListSet is a class that is a part of collection framework in Java.It has been available since Java version 1.6. ConcurrentSkipListSet  is a scalable concurrent NavigableSet implementation based on a ConcurrentSkipListMap.The...

16 minutes read.

Java Byte Code

Java byte code is really a powerful mechanism which makes Java a portable and platform-independent programming language. There are two software components which go along and make this byte code...

3 minutes read.

Types of Events in Java

One of Java's key ideas is the principle of an event. Events in Java are activities that result in a change in the state or behavior of an object. The...

4 minutes read.

Map of Map in Java

The map is now a Java interface for mapping keys to values. It is frequently necessary to use Map of Map (nested Map). Nested Maps are useful in various situations, including...

3 minutes read.

Java Generate Random String

Java Generate Random String In this tutorial, we will learn about to generate random string in Java. Random generation strings mean any string will be generated, which does not follow any...

7 minutes read.

Java Math decrementExact() Method

The decrementExact() method of Math class returns the argument which is decremented by one, throwing an exception is the result overflows an int or long. Syntax: public static int decrementExact (int a) Parameters: The...

1 minute read.

Java Pass-by-Reference

In Java, passing parameters can be done using one of two fundamental methods. Pass-by-value is used for the first and pass-by-reference is used for the second. One thing to keep...

2 minutes read.

How to Convert String to double in Java

How to Convert String to double in java It is used if we have to perform mathematical operations on the string that contains a double number. When we get data from...

3 minutes read.

Java StringBuffer vs StringBuilder

Java StringBuffer vs StringBuilder StringBuffer The StringBuffer class is used to create mutable string. StringBuffer shows writable and growable character sequences. Java StringBuffer program FileName: StringBufferExample.java // A basic program that demonstrates the working...

2 minutes read.

Java logger

Logging is a crucial Java feature that aids developers in identifying issues. The logging methodology is included with Java as the programming language. It offers the Logging API, which debuted...

7 minutes read.

Generic queue in Java

Before understanding how to implement a generic queue in java, one must know about generics and queue in java. Generics in Java Generics are parameterized types. The goal is to enable type...

6 minutes read.

Java Math cosh() Method

The cosh() method of Math class returns the first hyperbolic cosine((e+e)/2) of a double value. Syntax: public static double cosh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic cosine is to be...

2 minutes read.

Java Print Writer

PrintWriter: It is used to write output data from the file. It is the class of Java.io package. It inherits the properties of the Writer class. Writer Class: It is a class of...

4 minutes read.

How to Calculate Time Difference Between Two Dates in Java?

Date is being used extensively in Java to calculate date differences. While constructing an application, the date of joining an organisation, admission date, appointment date, and others might be included....

4 minutes read.

Java Networking

Networking Networking is a way of communicating the devices. It is made up of various technologies like computers, switches, routers that are interconnected and share data among themselves. The two common network protocols: 1. TCP/IP TCP stands for...

10 minutes read.