里斯本的地表沉降监测——PS监测及
743 2023-04-03 04:55:23
在 Java 中,自动为我们创建了 3 个流。所有这些流都与控制台相连。
1) System.out:标准输出流
2) System.in:标准输入流
3) System.err:标准错误流
OutputStream:Java application uses an output stream to write data to a destination; it may be a file, an array, peripheral device or socket.
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 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
InputStream class is an abstract class. It is the superclass of all classes representing an input stream of bytes.
Useful methods of InputStream
InputStream Hierarchy
Java FileReader 类用于从文件中读取数据。它以字节格式返回数据,如FileInputStream类。它是面向字符的类,用于在java中进行文件处理。
public class FileReader extends InputStreamReader
In this example, we are reading the data from the text file testout.txt using Java FileReader class.
import java.io.FileReader;
public class FileReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=**new*FileReader("D:\\testout.txt");
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}
}
假设您在“testout.txt”文件中有以下数据:Welcome to java
输出:Welcome to java
Java BufferedReader 类用于从基于字符的输入流中读取文本。它可以用于通过 readLine() 方法逐行读取数据,性能快速。它继承了Reader 类。
public class BufferedReader extends Reader
methods:
eg:
import java.io.*;
public class BufferedReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("D:\\testout.txt");
BufferedReader br=new BufferedReader(fr);
int i;
while((i=br.read())!=-1){
System.out.print((char)i);
}
br.close();
fr.close();
}
}
data in "testout.txt" file: Welcome to java.
Output: Welcome to java.
通过 InputStreamReader 和 BufferedReader 从控制台读取数据
import java.io.*;
public class BufferedReaderExample{
public static void main(String args[])throws Exception{ InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
System.out.println("Enter your name");
String name=br.readLine();
System.out.println("Welcome "+name);
}
}
Output:
Enter your name
Nakul Jain
Welcome Nakul Jain
从控制台读取数据直到用户写入停止的另一个示例:读取和打印数据,直到用户停止打印。
import java.io.*;
public class BufferedReaderExample{
public static void main(String args[])throws Exception{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
String name="";
while(!name.equals("stop")){
System.out.println("Enter data: ");
name=br.readLine();
System.out.println("data is: "+name);
}
br.close();
r.close();
}
}
Output:
Enter data: Nakul
data is: Nakul
Enter data: 12
data is: 12
Enter data: stop
data is: stop