Java面试题每日10问(15)

文章介绍了Java中的I/O流,包括OutputStream和InputStream的区别及其常用方法,以及FileInputStream和FileOutputStream在文件操作中的使用。还提到了BufferedInputStream和BufferedOutputStream用于提高性能的作用,过滤流(FilterStream)的概念,以及如何设置文件权限。此外,文章还讨论了从控制台获取输入的三种方式(BufferedReader,Scanner,Console)以及Java对象的序列化机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I/O Interview Questions

1.What do you understand by an IO stream?

  • The stream is a sequence of data that flows from source to destination.

  • It is composed of bytes.

  • In Java, three streams are created for us automatically.

    1. System.out: standard output stream
    2. System.in: standard input stream
    3. System.err: standard error stream

🔔Note

OutputStream vs InputStream

1)OutputStream
Java application uses an output stream to write data to a destination; it may be a file, an array, peripheral device or socket.

2)InputStream
Java application uses an input stream to read data from a source; it may be a file, an array, peripheral device or socket.

在这里插入图片描述

OutputStream class vs InputStream class

1)OutputStream class

  • OutputStream class is an abstract class.
  • It is the superclass of all classes representing an output stream of bytes.
  • An output stream accepts output bytes and sends them to some sink.

Useful methods of OutputStream

MethodDescription
1) public void write(int)throws IOExceptionis used to write a byte to the current output stream.
2) public void write(byte[])throws IOExceptionis used to write an array of byte to the current output stream.
3) public void flush()throws IOExceptionflushes the current output stream.
4) public void close()throws IOExceptionis used to close the current output stream.

OutputStream Hierarchy
在这里插入图片描述

2)InputStream class

  • InputStream class is an abstract class.
  • It is the superclass of all classes representing an input stream of bytes.

Useful methods of InputStream

MethodDescription
1) public abstract int read()throws IOExceptionreads the next byte of data from the input stream. It returns -1 at the end of the file.
2) public int available()throws IOExceptionreturns an estimate of the number of bytes that can be read from the current input stream.
3) public void close()throws IOExceptionis used to close the current input stream.

InputStream Hierarchy
在这里插入图片描述

2.What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?

  • The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented.
  • The ByteStream classes are used to perform input-output of 8-bit bytes whereas the CharacterStream classes are used to perform the input/output for the 16-bit Unicode system.
  • There are many classes in the ByteStream class hierarchy, but the most frequently used classes are FileInputStream and FileOutputStream.
  • The most frequently used classes CharacterStream class hierarchy is FileReader and FileWriter.

3.What are the super most classes for all the streams?

  • All the stream classes can be divided into two types of classes that are ByteStream classes and CharacterStream Classes.
  • The ByteStream classes are further divided into InputStream classes and OutputStream classes.
  • CharacterStream classes are also divided into Reader classes and Writer classes.
  • The SuperMost classes for all the InputStream classes is java.io.InputStream and for all the output stream classes is java.io.OutPutStream.
  • Similarly, for all the reader classes, the super-most class is java.io.Reader, and for all the writer classes, it is java.io.Writer.

4.What are the FileInputStream and FileOutputStream?

FileOutputStream

  • Java FileOutputStream is an output stream used for writing data to a file.
  • If you have some primitive values to write into a file, use FileOutputStream class.
  • You can write byte-oriented as well as character-oriented data through the FileOutputStream class.
  • However, for character-oriented data, it is preferred to use FileWriter than FileOutputStream.
public class A{
    public static void main(String args[]){
        try{
            FileOutputStream test=new FileOutputStream("C:\\projects\\a.txt");
            test.write(65);
            test.close();
            System.out.println("success...");
        }catch(Exception e){System.out.println(e);}
    }
}
success...

在这里插入图片描述

FileInputStream

  • Java FileInputStream class obtains input bytes from a file.
  • It is used for reading byte-oriented data (streams of raw bytes) such as image data, audio, video, etc.
  • You can also read character-stream data.
  • However, for reading streams of characters, it is recommended to use FileReader class.
public class A{
    public static void main(String args[]){
        try{
            FileInputStream test=new FileInputStream("C:\\projects\\a.txt");
            int i=test.read();
            System.out.println((char)i);
            test.close();
            System.out.println("success...");
        }catch(Exception e){System.out.println(e);}
    }
}

A
success...

5. What is the purpose of using BufferedInputStream and BufferedOutputStream classes?

  • Java BufferedOutputStream class is used for buffering an output stream.
  • It internally uses a buffer to store data.
  • It adds more efficiency than to write data directly into a stream. So, it makes the performance fast.
  • Whereas, Java BufferedInputStream class is used to read information from the stream.

6.How to set the Permissions to a file in Java?

  • In Java, FilePermission class is used to alter the permissions set on a file.
  • Java FilePermission class contains the permission related to a directory or file. All the permissions are related to the path.

The path can be of two types:

  • D:\IO\-:
    It indicates that the permission is associated with all subdirectories and files recursively.
  • D:\IO\*:
    It indicates that the permission is associated with all directory and files within this directory excluding subdirectories.
public class A{

    public static void main(String[] args) throws IOException {
        String srg = "C:\\IO projects\\a.txt";
        FilePermission file1 = new FilePermission("C:\\IO projects\\-", "read");

        PermissionCollection permission = file1.newPermissionCollection();
        permission.add(file1);

        FilePermission file2 = new FilePermission(srg, "write");
        permission.add(file2);

        if(permission.implies(new FilePermission(srg, "read,write"))) {
            System.out.println("Read, Write permission is granted for the path "+srg );
        }else {
            System.out.println("No Read, Write permission is granted for the path "+srg);
        }
    }
}

Read, Write permission is granted for the path C:\IO projects\a.txt

7.What are FilterStreams?

  • FilterStream classes are used to add additional functionalities to the other stream classes.
  • FilterStream classes act like an interface which read the data from a stream, filters it, and pass the filtered data to the caller.
  • The FilterStream classes provide extra functionalities like adding line numbers to the destination file, etc.

8.What is an I/O filter?

  • An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.
  • Many Filter classes that allow a user to make a chain using multiple input streams. It generates a combined effect on several filters

9.In Java, How many ways you can take input from the console?

3 ways by using

  1. Using BufferedReader class
  2. Using Scanner class
  3. Using Console class
  1. Using BufferedReader class

we can take input from the console by wrapping System.in into an InputStreamReader and passing it into the BufferedReader.
It provides an efficient reading as the input gets buffered.

public class A{

    public static void main(String[] args) throws IOException {
        System.out.println("what's your name?");
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String name = reader.readLine();
        System.out.println(name);
    }
}

what's your name?
Amy (input context)
Amy 
  1. Using Scanner class

The Java Scanner class breaks the input into tokens using a delimiter that is whitespace by default.
It provides many methods to read and parse various primitive values. Java Scanner class is widely used to parse text for string and primitive types using a regular expression. Java Scanner class extends Object class and implements Iterator and Closeable interfaces.

public class A{

    public static void main(String[] args){
        String str = "what's your name?/My name is Amy";
        //Create scanner with the specified String Object    
        Scanner scanner = new Scanner(str);
        System.out.println("Boolean Result: "+scanner.hasNextBoolean());
        scanner.useDelimiter("/");
        //Printing the tokenized Strings
        System.out.println("---Tokenizes String---");

        while(scanner.hasNext()){
            System.out.println(scanner.next());
        }
        //Display the new delimiter
        System.out.println("Delimiter used: " +scanner.delimiter());
        scanner.close();
    }
}

Boolean Result: false
---Tokenizes String---
what's your name?
My name is Amy
Delimiter used: /
  1. Using Console class
  • The Java Console class is used to get input from the console.
  • It provides methods to read texts and passwords.
  • If you read the password using the Console class, it will not be displayed to the user.
  • The java.io.Console class is attached to the system console internally.
  • The Console class is introduced since 1.5. Consider the following example.
public class A{
    public static void main(String[] args){
        Console c = System.console();
        System.out.println("Enter your name: ");
        String n = c.readLine();
        System.out.println("Welcome "+n);
    }
}
Enter your name: 
Exception in thread "main" java.lang.NullPointerException
	at model.A.main(A.java:15)

Serialization Interview Questions

10.What is serialization?

  • Serialization in Java is a mechanism of writing the state of an object into a byte stream.
  • It is used primarily in Hibernate, RMI, JPA, EJB and JMS technologies.
  • It is mainly used to travel object’s state on the network (which is known as marshaling).
  • Serializable interface is used to perform serialization.
  • It is helpful when you require to save the state of a program to storage such as the file.
  • At a later point of time, the content of this file can be restored using deserialization. It is also required to implement RMI(Remote Method Invocation).
  • With the help of RMI, it is possible to invoke the method of a Java object on one machine to another machine.

For serializing the object, we call the writeObject() method of ObjectOutputStream class, and for deserialization we call the readObject() method of ObjectInputStream class.

Advantages of Java Serialization
It is mainly used to travel object’s state on the network (that is known as marshalling).
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值