Отличие reader от inputstream java

Русские Блоги

Разница между InputStream и Reader, FileInputStream и FileReader

Во-первых, разница между InputStream и Reader

Как InputStream, так и Reader могут использоваться для чтения данных (чтения данных из файла или чтения данных из сокета), основные различия заключаются в следующем:

InputStream используется для чтения двоичных чисел (потоков байтов), а Reader — для чтения текстовых данных, то есть символов Unicode. Так в чем же разница между двоичными числами и текстовыми данными? По сути, все содержимое считывается байтами. Чтобы преобразовать байты в текст, необходимо указать метод кодирования. Считыватель может закодировать поток байтов и преобразовать его в текст. Конечно, в этом процессе преобразования используется метод кодирования, который по умолчанию использует метод кодирования системы для кодирования потока байтов. Также можно явно указать метод кодирования, например «UTF-8». Хотя эта концепция очень проста, Java-программисты часто допускают ошибки кодирования, и наиболее распространенной ошибкой является не указание метода кодирования. При чтении файлов или чтении данных из сокетов, если не указан правильный метод кодирования, считанные данные могут быть искажены, что может привести к потере данных.

Во-вторых, разница между FileInputStream и FileReader

FileInputStream и FileReader имеют сходные различия, они используются для чтения данных из файла, но FileInputStream используется для чтения двоичных данных (байтовый поток) из файла, а FileReader используется для чтения символьных данных из файла.

FileReader наследуется от InputStreamReader, он использует либо системный метод кодирования по умолчанию, либо метод кодирования, используемый InputStreamReader. Следует отметить, что InputStreamReader кэширует кодировку символов, поэтому после создания объекта InputStreamReader, если вы измените кодировку символов, это не будет иметь никакого эффекта. Вот пример использования Filelnputstream и FileReader:



Результат выполнения программы:

7465737420726561642066696c65
test read file

Как видно из приведенного выше кода, FilelnputStream считывает данные способом чтения байтов за байтом, поэтому скорость чтения будет ниже. Метод блокировки, он либо читает байт, либо блокирует (ожидая данных, которые можно прочитать). Возвращаемое значение этого метода — количество прочитанных байтов. Когда будет прочитан конец файла, он вернет 1. В примере использования FileInputStream каждый цикл читает один байт, а затем преобразует его в шестнадцатеричный вывод строки. Метод read в FileReaderI читает по одному символу за раз, пока не будет прочитан конец файла, и этот метод возвращает -1.

ШанхайШанг Сюетанг Обучение JavaРазница между FileInputStream и FileReader для технических галантерейных изделий объясняется здесь. Дополнительные статьи о знаниях технологии Java см. В других статьях этого блога. Если вам нужны учебные материалы по Java, оставьте комментарий. Шан Xuetang Java полный набор подробных учебных материалов видео и Python400 набор видео и учебное пособие для программиста, очень сухие товары.

Читайте также:  Override all css styles

Источник

Reader Vs InputStream classes in Java

The Reader and InputStream classes in Java are used for reading data from input sources, but they differ in their functionality and the type of data they handle. Here is a detailed explanation of the differences between Reader and InputStream:

Functionality

  1. Reader:The Reader class is designed for reading character-based data. It provides methods for reading characters, character arrays, and lines of text from the input source.
  2. InputStream:The InputStream class is designed for reading byte-based data. It provides methods for reading individual bytes, byte arrays, and blocks of binary data from the input source.

Character vs. Byte data:

  1. Reader:The Reader class reads data as characters. It is suitable for handling text data, such as reading from text files, network sockets, or other sources that contain character-based data.
  2. InputStream:The InputStream class reads data as bytes. It is suitable for handling binary data, such as reading from image files, audio files, or network streams that transmit raw byte data.

Encoding

  1. Reader:The Reader class supports character encoding and can handle different character encodings, such as UTF-8, ASCII, or ISO-8859-1. It allows you to specify the character encoding when reading text data.
  2. InputStream:The InputStream class does not perform any character encoding. It reads and provides raw bytes as they are, without any interpretation of the data as characters.

Hierarchy

  1. Reader:The Reader class is a part of the Java IO hierarchy and extends the java.io.Reader class. It provides a common set of methods for reading characters and is a superclass for more specific Reader implementations like FileReader or BufferedReader.
  2. InputStream:The InputStream class is also a part of the Java IO hierarchy and extends the java.io.InputStream class. It provides a common set of methods for reading bytes and is a superclass for more specific InputStream implementations like FileInputStream or BufferedInputStream.

Usage scenarios

  1. Reader:Use Reader when you need to read and process character-based data, such as reading text files, parsing XML, or processing strings.
  2. InputStream:Use InputStream when you need to read and process byte-based data, such as reading binary files, working with network sockets, or handling raw byte streams.

Conclusion

It’s important to choose the appropriate class (Reader or InputStream) based on the type of data you are working with and the operations you need to perform.

  1. Difference between Java and JavaScript?
  2. What is the difference between JDK and JRE?
  3. What gives Java its ‘write once and run anywhere’ nature?
  4. What is JVM and is it platform independent?
  5. What is Just-In-Time (JIT) compiler?
  6. What is the garbage collector in Java?
  7. What is NullPointerException in Java
  8. Difference between Stack and Heap memory in Java
  9. How to set the maximum memory usage for JVM?
  10. What is numeric promotion?
  11. Why do we need Generic Types in Java?
  12. What does it mean to be static in Java?
  13. What are final variables in Java?
  14. How Do Annotations Work in Java?
  15. How do I use the ternary operator in Java?
  16. What is instanceof keyword in Java?
  17. How ClassLoader Works in Java?
  18. What are fail-safe and fail-fast Iterators in Java
  19. What are method references in Java?
  20. «Cannot Find Symbol» compile error
  21. Difference between system.gc() and runtime.gc()
  22. How to convert TimeStamp to Date in Java?
  23. Does garbage collection guarantee that a program will not run out of memory?
  24. How setting an Object to null help Garbage Collection?
  25. How do objects become eligible for garbage collection?
  26. How to calculate date difference in Java
  27. Difference between Path and Classpath in Java
  28. Is Java «pass-by-reference» or «pass-by-value»?
  29. Difference between static and nonstatic methods java
  30. Why Java does not support pointers?
  31. What is a package in Java?
  32. What are wrapper classes in Java?
  33. What is singleton class in Java?
  34. Difference between Java Local Variable, Instance Variable and a Class Variable?
  35. Can a top level class be private or protected in Java
  36. Are Polymorphism , Overloading and Overriding similar concepts?
  37. How to Use Locks in Java
  38. Why Multiple Inheritance is Not Supported in Java
  39. Why Java is not a pure Object Oriented language?
  40. Static class in Java
  41. Difference between Abstract class and Interface in Java
  42. Why do I need to override the equals and hashCode methods in Java?
  43. Why does Java not support operator overloading?
  44. What’s meant by anonymous class in Java?
  45. Static Vs Dynamic class loading in Java
  46. Why am I getting a NoClassDefFoundError in Java?
  47. How to Generate Random Number in Java
  48. What’s the meaning of System.out.println in Java?
  49. What is the purpose of Runtime and System class in Java?
  50. The finally Block in Java
  51. Difference between final, finally and finalize
  52. What is try-with-resources in java?
  53. What is a stacktrace?
  54. Why String is immutable in Java ?
  55. What are different ways to create a string object in Java?
  56. Difference between String and StringBuffer/StringBuilder in Java
  57. Difference between creating String as new() and literal | Java
  58. How do I convert String to Date object in Java?
  59. How do I create a Java string from the contents of a file?
  60. What actually causes a StackOverflow error in Java?
  61. Why is char[] preferred over String for storage of password in Java
  62. What is I/O Filter and how do I use it in Java?
  63. Serialization and Deserialization in Java
  64. Understanding transient variables in Java
  65. What is Externalizable in Java?
  66. What is the purpose of serialization/deserialization in Java?
  67. What is the Difference between byte stream and Character streams
  68. How to append text to an existing file in Java
  69. How to convert InputStream object to a String in Java
  70. Introduction to Java threads
  71. What is synchronization Java?
  72. Static synchronization Vs non static synchronization in Java
  73. Deadlock in Java with Examples
  74. What is Daemon thread in Java
  75. Difference between implements Runnable and extends Thread in Java
  76. What is the volatile keyword in Java
  77. What are the basic interfaces of Java Collections Framework
  78. What are the differences between ArrayList and Vector in Java
  79. What is the difference between ArrayList and LinkedList?
  80. What is the difference between List and Set in Java
  81. Difference between HashSet and HashMap in Java
  82. Difference between HashMap and Hashtable in Java?
  83. How does the hashCode() method of java works?
  84. Difference between capacity() and size() of Vector in Java
  85. What is a Java ClassNotFoundException?
  86. How to fix java.lang.UnsupportedClassVersionError
Читайте также:  Эмулятор командной строки conemu python

Источник

Difference Between an InputStream and a Reader in Java

skrasool

skrasool

Both InputStream and Reader are abstractions to read data from source, which can be either file or socket, but main difference between them is, InputStream is used to read binary data, while Reader is used to read text data, precisely Unicode characters. So what is difference between binary and text data? well everything you read is essentially bytes, but to convert a byte to text, you need a character encoding scheme. Reader classes uses character encoding to decode bytes and return characters to caller. Reader can either use default character encoding of platform on which your Java program is running or accept a Charset object or name of character encoding in String format e.g. “UTF-8”. Despite being one of the simplest concept, lots of Java developers make mistakes of not specifying character encoding, while reading text files or text data from socket. Remember, if you don’t specify correct encoding, or your program is not using character encoding already present in protocol e.g. encoding specified in “Content-Type” for HTML files and encoding presents in header of XML files, you may not read all data correctly. Some characters which are not present in default encoding, may come up as ? or little square.

An InputStream is the raw method of getting information from a resource. It grabs the data byte by byte without performing any kind of translation. If you are reading image data, or any binary file, this is the stream to use.

A Reader is designed for character streams. If the information you are reading is all text, then the Reader will take care of the character decoding for you and give you unicode characters from the raw input stream. If you are reading any type of text, this is the stream to use.

Читайте также:  Прочитать файл java android

You can wrap an InputStream and turn it into a Reader by using the InputStreamReader class.

Reader reader = new InputStreamReader(inputStream);

input-stream

Output Stream

Источник

Оцените статью