자바 io 조작 코드

8934 단어
표준 장치 System. in 읽 기 데이터
import java.io.*;

--------------------------------------------------------------------------------

표준 출력 System. out 은 인쇄 스 트림 PrintStream -------------------------------------------------------------------
import java.io.*;
public class PrintStandardOutput {
public static void main(String[] args) {
String myAnswer = "No, and that's final,";
System.out.println("Hello World of Java");
System.out.println("The answer is " + myAnswer + " at this time.");
PrintWriter pw = new PrintWriter(System.out);
pw.println("The answer is " + myAnswer + " at this time.");
int i = 42;
pw.println(i + '=' + " the answer.");
pw.println("Note: " + i + '=' + " the answer.");
pw.println(i + "=" + " the answer.");
pw.println(i + ('=' + " the answer."));
pw.close();
}
}
한 텍스트 파일 을 읽 으 려 면
BufferedReader is = new BufferedReader (new FileReader ("xxxx. text")); BufferedOutputStream by teout = new BufferedOutputStream (new FileOutputStream ("XX. dat")) 읽 기; / / 텍스트 에 쓰기!
-----------------------------------------------  at 04-09-20 10:49     aeonsun 네티즌 은 import java. io. *; public class OpenFileByName {public static void main (String [] args) throws IOException {BufferedReader is = new BufferedReader (new FileReader ("myFile. txt"); BufferedOutputStream bytesOut = new BufferedOutputStream ("bytes. dat");
// Code here to read from is, write to bytesOut
bytesOut.close();}} at 04-09-20 10:50     aeonsun 네티즌: import java. io. *;
public class FileIO {
private FileIO() { }
public static void copyFile(String inName, String outName)throws FileNotFoundException, IOException {BufferedInputStream is = new BufferedInputStream(new FileInputStream(inName));BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(outName));copyFile(is, os, true);}
/** Copy a file from an opened InputStream to opened OutputStream */public static void copyFile(InputStream is, OutputStream os, boolean close) throws IOException {int b; while ((b = is.read()) != -1) {os.write(b);}is.close();if (close)os.close();}
public static void copyFile(Reader is, Writer os, boolean close) throws IOException {int b; while ((b = is.read()) != -1) {os.write(b);}is.close();if (close)os.close();}
public static void copyFile(String inName, PrintWriter pw, boolean close) throws FileNotFoundException, IOException {BufferedReader is = new BufferedReader(new FileReader(inName));copyFile(is, pw, close);}
public static String readLine(String inName)throws FileNotFoundException, IOException {BufferedReader is = new BufferedReader(new FileReader(inName));String line = null;line = is.readLine();is.close();return line;}
protected static final int BLKSIZ = 8192;
public void copyFileBuffered(String inName, String outName) throwsFileNotFoundException, IOException {InputStream is = new FileInputStream(inName);OutputStream os = new FileOutputStream(outName);int count = 0; byte b[] = new byte[BLKSIZ]; while ((count = is.read(b)) != -1) {os.write(b, 0, count);}is.close();os.close();}
public static String readerToString(Reader is) throws IOException {StringBuffer sb = new StringBuffer();char[] b = new char[BLKSIZ];int n;
while ((n = is.read(b)) > 0) {sb.append(b, 0, n);}
return sb.toString();}
public static String inputStreamToString(InputStream is)throws IOException {return readerToString(new InputStreamReader(is));}
public static void stringToFile(String text, String fileName)throws IOException {BufferedWriter os = new BufferedWriter(new FileWriter(fileName));os.write(text);os.flush();os.close();}
public static BufferedReader openFile(String fileName)throws IOException {return new BufferedReader(new FileReader(fileName));}} at 04-09-20 10:50     aeonsun 네티즌: import java, io. *;
class fileprocess{
public static void main (String args []) {int b; byte buffer [] = new byte [1000]; try {b = System. out. read (buffer); / / 쓰기 위해 데 이 터 를 액세스 합 니 다! FileOutputStream out = new FileOotputStream ("line. text"); out. write (buffer, 0, b); / / / 쓰기! 바이트 버퍼 파일 흐름 의 관계 주의] catch (IOException e) {System. out. println ("error");}}}}  at 04-09-20 10:50     aeonsun 네티즌: import java, io. *;
public class read{public static void main (String args []] 0 {int b; bytbuffer = new byt[2000]; try {FileInInStreamreadfile = new FileInInInInStream ("XXX. java"); b = readfile (buffer, 0, 25000); try {String str= nre String (buffer, 0, b, "기본 값"); / / 구조 문자열 대상! System. out. printtln (str);} catch (대체 인 코딩 예외 가 없 음) {printStriStriStriStriStriStriStriStriStriStriStriStri(buffer, 0, b, "기본 값"); / / / 구조 문자열 대상! System. out. printtl(str);} catch (대체 인 코딩 예외 예외 가 없 음) {printStackTracTracTracTracTracTrac} catch( IOException e){ System.out.println(" error");}}}  at 04-09-20 10:51     aeonsun 네티즌 은 "--- --- --- -------------------------------------------------------------------------------------------------------
BufferedReader - fileReader 를 이용 하여 텍스트 파일 을 읽 습 니 다!
IO 에 서 는 바이트 흐름 인지 문자 흐름 인지 항상 주의해 야 한다.
 
class filewindow extends JFrame implements ActionListener {JTextArea text; BufferedReader in; JButton button; FileReader file; filewindow () {super ("파일 문자 흐름"); Container con = getContentPane (); text = new JTextArea (50, 50); text. setBackground (Color. blue); try {File f = new File ("E: / a. txt"); file = new FileReader (f); in = new BufferedReader (file); / * BufferedReader(Reader in) 구조 함수, * 파일 자체 문자 읽 기 흐름 FileReader 는 BufferedReader * 흐름 에 접속 하여 BufferedReader 의 대상 방법 으로 readLine () 을 효율적으로 줄 지어 읽 을 수 있 습 니 다! * /
} catch (FileNotFoundException e) {} catch (IOException e) {} button = new JButton ("읽 기"); button. addActionListener (this); con. setLayout (new BorderLayout ()); setSize (300, 200); setVisible (true);
con.add(text,"Center");con.add(button,"South");addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){setVisible(false);System.exit(0);}});
} public void actionPerformed (ActionEvent e) {String s; if (e. getSource () = button) try {while ((s = in. readLine ()! = null) text. append (s + '/ n); / 읽 은 문자 데 이 터 를 BufferString 으로 잠시 저장 할 수 있 습 니 다!} catch (IOException e1) {}} at 04-09-20 10:51     aeonsun 네티즌 은 "--- ----------------------------------------------------------------------------
public class RandomRead{final static String FILENAME="E://a.txt";protected String fileName;protected RandomAccessFile seeker;
public static void main(String[] argv) throws IOException {RandomRead r = new RandomRead(FILENAME);
System.out.println("Offset is " + r.readOffset());System.out.println("Message is /"" + r.readMessage() + "/".");}
/** Constructor: save filename, construct RandomAccessFile */public RandomRead(String fname) throws IOException {fileName = fname;seeker = new RandomAccessFile(fname, "rw");}
/** Read the Offset field, defined to be at location 0 in the file. */public int readOffset() throws IOException {seeker.seek(0);seeker.writeChars(FILENAME); // move to very beginningreturn seeker.readInt(); // and read the offset}
/** Read the message at the given offset */public String readMessage() throws IOException {seeker.seek(120); // move to wherereturn seeker.readLine(); // and read the String}}  at 04-09-20 10:51     일부 댓 글: axman
힘 들 게 썼 다. 더 이상 말 하고 싶 지 않 았 지만 기술 에 대한 책임 정신 으로 말 했다.
I / O 에 대한 이 해 는 3 급 수준 (자바 IO 가 10 급 이면) 에 속 합 니 다. I / O 차원 에 익숙 하지 않 은 자바 IO 는 주로 자바. io 가방 과 자바. nio 가방 을 포함 합 니 다.
java. io 는 주로 네 개의 인터페이스 에서 연 장 됩 니 다. 바이트: InputStream / OutputStream, 그 다음은 패키지, 필터, 특정 대상 처리 의 구체 적 인 실현 클래스 입 니 다. 문자: Reader / Writer (원문 에서 Writer 인터페이스 까지 모두 Write 로 쓴 것 은 이 인 터 페 이 스 를 전혀 모 르 는 것 을 설명 할 수 있 습 니 다. Writer 인 터 페 이 스 를 자주 사용 하면 Writer 와 Write 도 구분 하지 못 하고 실수 가 아니 라 모두 Write 입 니 다)
상기 네 개의 인터페이스 에서 밑 층 은 모두 바이트 의 차단 방식 으로 흐른다.
java. io 는 주로 블록 조작 블록 (Buffer) 을 위주 로 하고 설정 할 수 있 는 블록 과 비음 색 모드 를 통 해 데이터 출력 입력 의 성능 을 크게 향상 시 켰 다. 또한 채널 을 선택 기 모드 의 제 어 를 통 해 같은 출력 입력 채널 에서 여러 사용자 가 동시에 데이터 입력 을 할 수 있다. 예 를 들 어 하나의 Socket 포트 는 동시에 무한 다 (이론 적 으로 제한 되 지 않 음)클 라 이언 트 가 동시에 방문 합 니 다. 바로 전형 적 인 I / O 다 중 재 활용 기술 입 니 다. 
public class systemin
{
public static void main(String args[])
{try {/ 흐름 변환!
BufferedReader is=new BufferedReader(new InputStreamReader(System.in))
String inputline=null;
while((inputline=is.readLine())!=null)
System.out.println(inputline);
is.close();
}
catch(IOException e)
{ System,out.println("IOXE: "+e);
}
}
}

좋은 웹페이지 즐겨찾기