J2SE 코드 예 수집 (IO) 2
//
package io;
import java.io.IOException;
public class TestSystemInRead {
public static void main(String[] args) {
int c;
try {
while((c = System.in.read())!=0) {
System.out.write(c);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
//
package io;
import java.io.IOException;
public class TestSystemInRead {
public static void main(String[] args) {
try {
byte[] b = new byte[100];
System.in.read(b);
System.out.write(b,0,100);
} catch (IOException e) {
e.printStackTrace();
}
}
}
//
package io;
import java.io.IOException;
public class TestSystemInRead {
public static void main(String[] args) {
try {
while(true){
byte[] b = new byte[100];
System.in.read(b);// b, ,
String str = new String(b);
System.out.println(str);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
package io;
import java.io.FileNotFoundException;
import java.io.IOException;
//RandomAccessFile ,
import java.io.RandomAccessFile;
public class TestRandomAccessFile {
public static void main(String[] args) {
try {
RandomAccessFile rafile = new RandomAccessFile("f:/testrw.txt" ,"rw");
// byte[] bw = new byte[3];
// bw[0] = 100;//d
// bw[1] = 101;//e
// bw[2] = 102;//f
// rafile.write(bw);
//rafile.writeBoolean(true);
rafile.writeBytes("AAAA");
//rafile.writeChars("DDDD");
rafile.writeUTF(" ");
//read
rafile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
}
}
// , ,
// ,
package io;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class TestPipedInputStream {
public static void main(String[] args) {
try {
PipedOutputStream pos = new PipedOutputStream();
PipedInputStream pis = new PipedInputStream(pos);
//
byte[] b = new byte[3];
b[0] = 100;
b[1] = 101;
b[2] = 102;
pos.write(b);
//
while(pis.available()>0) {
int c = pis.read();
System.out.print((char)(c));
}
pis.close();
pos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
package io;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
// ,
public class TestPipedOutputStream {
public static void main(String[] args) {
Sender sender = new Sender();
PipedOutputStream out = sender.getOutputStream();
Receiver receiver = new Receiver();
PipedInputStream in = receiver.getInputStream();
try {
out.connect(in);
} catch (IOException e) {
e.printStackTrace();
}
new Thread(sender).start();
new Thread(receiver).start();
}
}
//
class Sender extends Thread {
private PipedOutputStream out = new PipedOutputStream();
public PipedOutputStream getOutputStream() {
return out;
}
public void run() {
String s = new String ("My heart will go on, i love u!");
try {
out.write(s.getBytes());
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//
class Receiver extends Thread{
private PipedInputStream in = new PipedInputStream();
public PipedInputStream getInputStream() {
return in;
}
public void run() {
String s = null;
byte[] buf = new byte[1024];
try {
int len = in.read(buf);
s = new String(buf,0,len);
System.out.println("receive:"+ s);
} catch (IOException e) {
e.printStackTrace();
}
}
}
package io;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.LineNumberInputStream;
//LineNumberInputStream , ,
public class TestLineNumberStream {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("f:\\test1.txt");
LineNumberInputStream lis = new LineNumberInputStream(fis);
DataInputStream dis = new DataInputStream(lis);
String line;
while((line = dis.readLine())!=null) {
System.out.println(lis.getLineNumber()+": " +line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
package io;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PushbackInputStream;
//
public class TestPushbackInputStream {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("f:\\test1.txt");
PushbackInputStream pis = new PushbackInputStream(fis);
int c = pis.read();
System.out.println((char)c);
pis.unread(c);//
c= pis.read();
System.out.println((char)c);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
package io;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
//Windows ISO8859-1, ANSI
// UTF-8
public class TestCharsetChanged {
public static void main(String[] args) {
Charset cset = Charset.forName("UTF-8");
// Unicode
String str = " , , ,SS";
ByteBuffer buffer = cset.encode(str);
byte[] bytes = buffer.array();
// , 。
// ByteBuffer wrap 。
ByteBuffer bbuf = ByteBuffer.wrap(bytes);
CharBuffer cbuf = cset.decode(bbuf);
String str1 = cbuf.toString();
System.out.println(str1);
}
}
package io;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.StringTokenizer;
public class DataFileTest {
public static void main(String[] args) {
Employee[] staff = new Employee[3];
staff[0] = new Employee("Elena",7600,1987,02,13);
staff[1] = new Employee("Cathrine",8700,1983,02,13);
staff[2] = new Employee("Stephon",9800,1981,03,23);
try {
//save all employee records to the file employee.dat
PrintWriter out = new PrintWriter(new FileWriter("f:\\employee.dat"));
writeData(staff,out);
out.close();
//
BufferedReader in = new BufferedReader(new FileReader("f:\\employee.dat"));
Employee[] newstaff = readData(in);
for(Employee e: newstaff) {
System.out.println(e.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
}
static void writeData(Employee[] employees, PrintWriter out) throws IOException {
out.println(employees.length);//write number of the array employees
for(Employee e :employees) {
e.writeData(out);
}
}
static Employee[] readData(BufferedReader in) throws IOException {
int n = Integer.parseInt(in.readLine());
Employee[] employees = new Employee[n];
for(int i=0;i<n;i++) {
employees[i] = new Employee();
employees[i].readData(in);
}
return employees;
}
}
class Employee {
private String name ;
private double salary;
private Date hireDay;
public Employee(){}
public Employee(String n, double s, int year, int month, int day) {
name = n;
salary = s;
GregorianCalendar calendar = new GregorianCalendar(year, month-1, day);
hireDay = calendar.getTime();
}
public void writeData(PrintWriter out) throws IOException {
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(hireDay);
out.println(name+ "|" + salary + "|"
+ calendar.get(Calendar.YEAR)+"|"
+(calendar.get(Calendar.MONTH)+1)+"|"
+ calendar.get(Calendar.DAY_OF_MONTH)
);
}
public void readData(BufferedReader in) throws IOException{
String s = in.readLine();
StringTokenizer t = new StringTokenizer(s,"|");
name = t.nextToken();
salary = Double.parseDouble(t.nextToken());
int y = Integer.parseInt(t.nextToken());
int m = Integer.parseInt(t.nextToken());
int d = Integer.parseInt(t.nextToken());
GregorianCalendar calendar = new GregorianCalendar();
calendar.set(y, m-1, d);
hireDay = calendar.getTime();
}
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
public Date getHireDay() {
return hireDay;
}
public void raiseSalary(double byPercent) {
double raise = salary * byPercent /100;
salary += raise;
}
public String toString() {
return this.getClass().getName()+"[name="+name + ",salary="+salary +
",hireDay="+hireDay +"]";
}
}
NIO package io;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.zip.CRC32;
// 32 (CRC32)
public class NIOTest {
public static long checksumInputStream(String filename) throws IOException {
InputStream in = new FileInputStream(filename);
CRC32 crc = new CRC32();
int c;
while((c= in.read()) != -1) {
crc.update(c);
}
return crc.getValue();
}
public static long checksumBufferedInputStream(String filename) throws IOException {
InputStream in = new BufferedInputStream(new FileInputStream(filename));
CRC32 crc = new CRC32();
int c;
while((c= in.read()) != -1) {
crc.update(c);
}
return crc.getValue();
}
public static long checksumRandomAccessFile(String filename) throws IOException {
RandomAccessFile file = new RandomAccessFile(filename,"r");
long length = file.length();
CRC32 crc = new CRC32();
for(long p=0; p<length; p++) {
file.seek(p);
int c = file.readByte();
crc.update(c);
}
return crc.getValue();
}
// NIO
public static long checksumMappedFile(String filename) throws IOException {
FileInputStream in = new FileInputStream(filename);
//FileChannel , , 、 、
FileChannel channel = in.getChannel();
CRC32 crc = new CRC32();
int length = (int) channel.size();
//
MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, length);
for(int p=0; p<length; p++) {
int c = buffer.get(p);
crc.update(c);
}
return crc.getValue();
}
public static void main(String[] args) throws IOException {
System.out.println("InputStream");
long start = System.currentTimeMillis();
long crcValue = checksumInputStream("f:\\quanxian.xml");
long end = System.currentTimeMillis();
System.out.println(Long.toHexString(crcValue));
System.out.println((end-start)+ "milliseconds");//1250milliseconds
System.out.println("BufferedInputStream");
start = System.currentTimeMillis();
crcValue = checksumBufferedInputStream("f:\\quanxian.xml");
end = System.currentTimeMillis();
System.out.println(Long.toHexString(crcValue));
System.out.println((end-start)+ "milliseconds");//47milliseconds
System.out.println("RandomAccessFile");
start = System.currentTimeMillis();
crcValue = checksumRandomAccessFile("f:\\quanxian.xml");
end = System.currentTimeMillis();
System.out.println(Long.toHexString(crcValue));
System.out.println((end-start)+ "milliseconds");//1860milliseconds
System.out.println("MappedFile");
start = System.currentTimeMillis();
crcValue = checksumMappedFile("f:\\quanxian.xml");
end = System.currentTimeMillis();
System.out.println(Long.toHexString(crcValue));
System.out.println((end-start)+ "milliseconds");//109milliseconds
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
java 입출력 I/O스트림(stream) 자바에서 입출력을 수행하려면 두 대상을 연결하고 데이터를 전송할 수 있는 무언가가 필요한데 이것을 스트림(stream)이라고 정의했다. 스트림은 단방향 통신만 가능하기 때문에 하나의 스트림으로 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.