찾다
Javajava지도 시간Java의 DataInputStream

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 :

Java의 DataInputStream

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 :

Java의 DataInputStream

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 :

Java의 DataInputStream

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 :

Java의 DataInputStream

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 :

Java의 DataInputStream

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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
Java 플랫폼은 어떻게 독립적입니까?Java 플랫폼은 어떻게 독립적입니까?May 09, 2025 am 12:11 AM

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

Java의 플랫폼 독립성에 대한 진실 : 정말 간단합니까?Java의 플랫폼 독립성에 대한 진실 : 정말 간단합니까?May 09, 2025 am 12:10 AM

java'splatformincceldenceisisnotsimple; itinvolvescomplex

Java 플랫폼 독립성 : 웹 응용 프로그램의 장점Java 플랫폼 독립성 : 웹 응용 프로그램의 장점May 09, 2025 am 12:08 AM

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

JVM 설명 : Java Virtual Machine에 대한 포괄적 인 가이드JVM 설명 : Java Virtual Machine에 대한 포괄적 인 가이드May 09, 2025 am 12:04 AM

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

Java의 주요 기능 : 왜 최고의 프로그래밍 언어로 남아 있는지Java의 주요 기능 : 왜 최고의 프로그래밍 언어로 남아 있는지May 09, 2025 am 12:04 AM

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

Java 플랫폼 독립성 : 개발자에게 무엇을 의미합니까?Java 플랫폼 독립성 : 개발자에게 무엇을 의미합니까?May 08, 2025 am 12:27 AM

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

첫 번째 사용을 위해 JVM을 설정하는 방법은 무엇입니까?첫 번째 사용을 위해 JVM을 설정하는 방법은 무엇입니까?May 08, 2025 am 12:21 AM

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

내 제품의 Java 플랫폼 독립성을 어떻게 확인할 수 있습니까?내 제품의 Java 플랫폼 독립성을 어떻게 확인할 수 있습니까?May 08, 2025 am 12:12 AM

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

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

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

뜨거운 도구

안전한 시험 브라우저

안전한 시험 브라우저

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

Dreamweaver Mac版

Dreamweaver Mac版

시각적 웹 개발 도구

SecList

SecList

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

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경

SublimeText3 Mac 버전

SublimeText3 Mac 버전

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