×

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

Java Lambda foreach

Before understanding lamda foreach, one must know about foreach loop in Java. foreach loop in Java Since J2SE 5.0, there has been a for-each loop in Java, also known as an extended...

4 minutes read.

Palindrome Partitioning problem in Java

In this article, you will be acknowledged about partitioning of the palindrome. It can be done in many ways. This article makes sure every method is discussed. Palindrome If a string remains...

6 minutes read.

Hidden classes in Java

There specifically are some APIs available in the market that generally is harmful to be used in our programs specifically literally, and until JDK 15, there, for all intents and...

4 minutes read.

Java String Reader

StreamReaderClass: This class is present in the java.io package. It is a character stream in which string act as a source.This method provides to read characters from a string. Character Stream: This class...

3 minutes read.

Java Command not found

Java Command not found error is displayed if Java is not installed on the computer or if the command prompt cannot find Java.exe to run the program. Our Java software...

3 minutes read.

Interface in Java

  Interface in Java In Java, the interface is just like a class that has only static constants and abstract methods. It is used to achieve polymorphism so that it can also...

6 minutes read.

Different Ways to Take Input from User in Java

Any information provided to a system for use is known as user input. Any responsive software or application must include user input. In Java, there are 4 different ways to...

5 minutes read.

How to calculate time complexity of any program in Java

Java : Java's syntax and principles are derived from the C and C++ languages. We know that java is one of the programming language. The main feature of java which is...

3 minutes read.

JIT in Java

What is JIT ? JIT stands for " Just in Time Compiler ". It is called "Just in time" because it is called at the very last moment when the interpretation...

5 minutes read.

File Operation in Java

In Java, a file is an Abstract data type. These are used to store the data which is related. Files are named storage locations. With a file we can perform...

7 minutes read.

Java String endsWith() method

Checks whether this String ends with the specified suffix or not. Syntax public boolean endsWith(String Suffix) Parameter Suffix : It takes suffix as a parameter  i.e. Sequence of characters Returns It returns true when the current...

1 minute read.

Difference Between Thread.start() and Thread.run()

In the Java programming language, the multi-threading concept consists of the start() and run() methods. Thread.start(): The thread's execution is initiated by invoking the start() method. The start() method operates two threads...

4 minutes read.

How to Solve the Deprecated Error in Java?

Deprecated Java methods should not be used because they are deprecated (often, there are better, more modern alternatives). API update. Until now, Java has kept everything backward compatible and never...

3 minutes read.

Stack Program in Java

Stack Program in Java The Stack class is part of the collection framework that inherits the Vector class. Thus, the Stack class can also be called a subclass of the Vector...

5 minutes read.

Java Integer compareTo() method

The compareTo() method of Integer class compares two Integer objects numerically. Syntax public static int compareTo(int anotherInteger) Parameters The parameter ‘anotherInteger’ represents the Integer to be compared. Specified by This method is specified by compareTo in...

2 minutes read.

Java Strings

String class is the most used class in Java programming language. The string is the sequence of characters, which is treated as objects in Java. Creating String objects We create String objects...

5 minutes read.

Balanced Prime Number in Java

This section will cover the definition of a balanced prime number as well as how to find one using a Java program. Balance Prime Number A prime number that is equivalent to...

5 minutes read.

Minimum Difference Between Groups of Size Two in Java

There is given an array with various integers in it. The goal is to divide the elements into distinct groups, each of which has just two, so that the difference...

3 minutes read.

Java Plot

Java Plot is a phrase in Java that is mostly used for plotting coordinates on a cartesian plane. Plotting graphs in Java is accomplished through the use of various core...

3 minutes read.

Java 9 Interface Private Method

Java 9 provides us the facility to include private methods inside the java interface. In java 8 and earlier versions, we are supposed to use only constant variables and abstract...

3 minutes read.