Java/자바 기본 문법
[자바] NIO 기반 바이트 스트림 & 문자 스트림 생성
가자미
2021. 3. 1. 13:27
NIO.2 기반 바이트 스트림 생성
public static void main(String[] args) {
Path fp = Paths.get("data.dat");//NIO기반
try(DataOutputStream out = new DataOutputStream(Files.newOutputStream(fp))){//NIO기반
out.writeInt(370);
out.writeDouble(3.14);
}
catch(IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Path fp = Paths.get("data.dat");
try(DataInputStream in = new DataInputStream(Files.newInputStream(fp))){
int num1 = in.readInt();
double num2 = in.readDouble();
}
catch(IOException e) {
e.printStackTrace();
}
}
NIO.2 기반 문자 스트림 생성
public static void main(String[] args) {
String ks = "hello";
String es = "hi!";
Path fp = Paths.get("String.txt");
try(BufferedWriter bw = Files.newBufferedWriter(fp)){
bw.write(ks,0,ks.length());
bw.newLine();
bw.write(es, 0, es.length());
}
catch(IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Path fp = Paths.get("String.txt");
try(BufferedReader br = Files.newBufferedReader(fp)){
String str;
while(true) {
str=br.readLine();
if(str==null)
break;
System.out.println(str);
}
}
catch(IOException e) {
e.printStackTrace();
}
}