In java, we use dataInputsream to read primitive data type. It read number other than bytes that are why it is called dataInputstream. In java, it is available in the Java.io package. Our java primitive class includeint, long, float etc., we read this primitive from input Stream. We use this DataInputStream in Java to read the data which is written by dataOutputStream.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
Syntax
public class DataInputStream extends FilterInputStream implements DataInput{}
Above is the class declaration fordataInputsream. It implements various class and interface. Below mentioned various class and interface which are extended and implements by dataInputsream:
Classes from very parent to child sequence:
- Object
- InputStream
- FilterInputStream
- DataInputStream
Various Interfaces are below :
- AutoCloseable
- DataInput
- Closeable
How does DataInputStream work in Java?
DataInputStream in Java it has the below constructor, which takes one parameter. This parameter is nothing but our inputStream from which we are going to read the data. Below find details of how constructor works:
- DataInputStream(InputStream in): If we use this constructor to create the DataInputStream in Java object, then we need to pass the inputStream as a parameter. In java, DataInputStream extends InputStream class, so it is the subclass for InputStream, so dataInpuutStream can use all the available methods in the parent class.
- If we want to use dataInpuutStream, we first need to create the object for that:
DataInputStream dataInputStream = new DataInputStream(new FileInputStream("your_data"));
In the above, we are creating an object for DataInputStream in Java by using its constructor where we can pass our inputStream for which we want to read our data.
- This class have the readByte() method through which we read our data.
DataInputStream ds = new DataInputStream(new FileInputStream("your_data")); ds.readByte();
- By using this method, we can read data from the above-passed inputstream. Below is the simple syntax to use dataInputStream in java:
DataInputStreamdataInputStream = new DataInputStream(newFileInputStream("file_name")); doubletoreadDouble = input.readDouble(); inttoread = input.read(); float toreadFloat = input.readFloat(); inttoreadInt = input.readInt(); input.close();
In the above simple syntax, we are getting an idea of how to use this class to read the primitive type in java (int, float, long, double etc.). Simple in the first step, we just create the object and pass our inputStream and using java in build methods to read data like int, float, double and one separate method named as read(). This DataInputStream in Java is always used with DataOuputStream as this is used to write our data. This class also contains various methods used to write data to a file. This has methods specific to int, double, float, etc. and vice versa. We also have methods to read this primitivetype data from a file.
Examples to Implement DataInputStream in Java
It has various method to read data from the input stream to read primitive type object like int, float, double, float, Boolean etc. Methods are mentioned below with example:
Example #1
longreadLong(): This method is used to read the long primitive type from the inpputstream.
Code:
package com.cont.article; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class DataInputStreamDemo { public static void main(String[] args) throws IOException { DataOutputStream dataOut = new DataOutputStream( new FileOutputStream("I:\\content_article\\MAR_2020\\file\\input.bin")); // here we are writing long to file. dataOut.writeLong(900); // close file. dataOut.close(); // To read data from file DataInputStream dataInputStream = new DataInputStream( new FileInputStream("I:\\content_article\\MAR_2020\\file\\input.bin")); long longData = dataInputStream.readLong(); dataInputStream.close(); System.out.println("longData is :: = " + longData); } }
Output :
Example #2
float readFloat(): This method is used to read the float primitive type from the inpputstream file provided.
Code:
package com.cont.article; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class DataInputStreamDemo { public static void main(String[] args) throws IOException { DataOutputStream dataOut = new DataOutputStream( new FileOutputStream("I:\\content_article\\MAR_2020\\file\\input.bin")); // here we are writing float to file. dataOut.writeFloat(67.00F); // close file. dataOut.close(); // To read data from file (float) DataInputStream dataInputStream = new DataInputStream( new FileInputStream("I:\\content_article\\MAR_2020\\file\\input.bin")); float floatData = dataInputStream.readFloat(); dataInputStream.close(); System.out.println("floatData is :: = " + floatData); } }
Output :
Example #3
intreadInt(): This method is used to read the int value from the inpputstream file.
Code:
package com.cont.article; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class DataInputStreamDemo { public static void main(String[] args) throws IOException { DataOutputStream dataOut = new DataOutputStream( new FileOutputStream("I:\\content_article\\MAR_2020\\file\\input.bin")); // here we are writing int to file. dataOut.writeInt(10); // close file. dataOut.close(); // To read data from file (int) DataInputStream dataInputStream = new DataInputStream( new FileInputStream("I:\\content_article\\MAR_2020\\file\\input.bin")); int intData = dataInputStream.readInt(); dataInputStream.close(); System.out.println("intData is :: = " + intData); } }
Output :
Example #4
double readDouble(): This method is used to read the double primitive type from inpputstream.
Code:
package com.cont.article; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class DataInputStreamDemo { public static void main(String[] args) throws IOException { DataOutputStream dataOut = new DataOutputStream( new FileOutputStream("I:\\content_article\\MAR_2020\\file\\input.bin")); // here we are writing double to file. dataOut.writeDouble(1000); // close file. dataOut.close(); // To read data from file (double) DataInputStream dataInputStream = new DataInputStream( new FileInputStream("I:\\content_article\\MAR_2020\\file\\input.bin")); double doubleData = dataInputStream.readDouble(); dataInputStream.close(); System.out.println("doubleData is :: = " + doubleData); } }
Output :
Example #5
char readChar(): This method is used to read char primitive from inpputstream. See the below example:
Code:
package com.cont.article; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class DataInputStreamDemo { public static void main(String[] args) throws IOException { DataOutputStream dataOut = new DataOutputStream( new FileOutputStream("I:\\content_article\\MAR_2020\\file\\input.bin")); // here we are writing char to file. dataOut.writeChar(100); // close file. dataOut.close(); // To read data from file (char) DataInputStream dataInputStream = new DataInputStream( new FileInputStream("I:\\content_article\\MAR_2020\\file\\input.bin")); char charData = dataInputStream.readChar(); dataInputStream.close(); System.out.println("charData is :: = " + charData); } }
Output :
Conclusion
DataInputStream in Java is basically used to read the data from the input stream we passed as an argument into the constructor as a file. It can read all primitive data types which are available in java. But this is not thread-safe; to provide thread safety, we need to go for others.
위 내용은 Java의 DataInputStream의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

Java는 JVM (Java Virtual Machines) 및 바이트 코드에 의존하는 "Write Once, Everywhere 어디에서나 Run Everywhere"디자인 철학으로 인해 플랫폼 독립적입니다. 1) Java Code는 JVM에 의해 해석되거나 로컬로 계산 된 바이트 코드로 컴파일됩니다. 2) 라이브러리 의존성, 성능 차이 및 환경 구성에주의하십시오. 3) 표준 라이브러리를 사용하여 크로스 플랫폼 테스트 및 버전 관리가 플랫폼 독립성을 보장하기위한 모범 사례입니다.

java'splatformincceldenceisisnotsimple; itinvolvescomplex

Java'SplatformIndenceBenefitsWebApplicationScodetorUnonySystemwithajvm, simplifyingDeploymentandScaling.Itenables : 1) EasyDeploymentAcrossDifferentservers, 2) SeamlessScalingAcrossCloudPlatforms, 3))

thejvmistheruntimeenvironmenmentforexecutingjavabytecode, Crucialforjava의 "WriteOnce, runanywhere"capability.itmanagesmemory, executesThreads, andensuressecurity, makingestement ofjavadeveloperStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandSmetsmentsMemory

javaremainsatopchoicefordevelopersdueToitsplatformindence, 객체 지향 데 디자인, 강력한, 자동 메모리 관리 및 compehensiveStandardlibrary

Java'splatforminceldenceMeansdeveloperscanwriteCodeOnceAndrunitonAnyDevicewithoutRecompiling.thisiSocievedTheRoughthejavirtualMachine (JVM), thisTecodeIntomachine-specificinstructions, hallyslatslatsplatforms.howev

JVM을 설정하려면 다음 단계를 따라야합니다. 1) JDK 다운로드 및 설치, 2) 환경 변수 설정, 3) 설치 확인, 4) IDE 설정, 5) 러너 프로그램 테스트. JVM을 설정하는 것은 단순히 작동하는 것이 아니라 메모리 할당, 쓰레기 수집, 성능 튜닝 및 오류 처리를 최적화하여 최적의 작동을 보장하는 것도 포함됩니다.

ToensureJavaplatform Independence, followthesesteps : 1) CompileIndrunyourApplicationOnMultiplePlatformsUsingDifferentOnsandjvMversions.2) Utilizeci/CDPIPELINES LICKINSORTIBACTIONSFORAUTOMATES-PLATFORMTESTING


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

안전한 시험 브라우저
안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

Dreamweaver Mac版
시각적 웹 개발 도구

SecList
SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

ZendStudio 13.5.1 맥
강력한 PHP 통합 개발 환경

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)