자바 프로 그래 밍 (고급 및 테마) - IO 흐름 과 직렬 화
77907 단어 Java
파일 클래스
/*
File ( )
File.separator //
, :e:\\work\\workspace\\ioDemo\\txt\\aaa.txt
, .classpath
f1.createNewFile(); ,
file.list();// String
*/
File f=new File("D:"+File.separator+"aaa"+File.separator+"aaa.txt");
/*
File f1=new File("D:"+File.separator+"aaa","aaa.txt");
File parent=new File("D:"+File.separator+"aaa");
File child=new File(parent,"aaa.txt");*/
다음은 그것 의 몇 가지 방법 이다.
번호
방법.
소개 하 다.
1
public String getName()
추상 적 인 경로 이름 으로 표 시 된 파일 이나 디 렉 터 리 의 이름 을 되 돌려 줍 니 다.
2
public String getParent()
이 추상 적 인 경로 이름 의 부모 경로 이름 의 경로 이름 문자열 을 되 돌려 줍 니 다. 이 경로 이름 이 부모 디 렉 터 리 를 지정 하지 않 으 면 null 로 돌아 갑 니 다.
3
public File getParentFile()
이 추상 적 인 경로 이름 의 부모 경로 이름 의 추상 적 인 경로 이름 을 되 돌려 줍 니 다. 이 경로 이름 이 부모 디 렉 터 리 를 지정 하지 않 으 면 null 로 돌아 갑 니 다.
4
public String getPath()
이 추상 적 인 경로 이름 을 경로 이름 문자열 로 변환 합 니 다.
5
public boolean isAbsolute()
이 추상 적 인 경로 이름 이 절대 경로 이름 인지 테스트 합 니 다.
6
public String getAbsolutePath()
추상 적 인 경로 이름 의 절대 경로 이름 문자열 을 되 돌려 줍 니 다.
7
public boolean canRead()
프로그램 이 이 추상 적 인 경로 이름 으로 표 시 된 파일 을 읽 을 수 있 는 지 시험 합 니 다.
8
public boolean canWrite()
프로그램 이 이 추상 적 인 경로 이름 으로 표 시 된 파일 을 수정 할 수 있 는 지 시험 합 니 다.
9
public boolean exists()
이 추상 적 인 경로 이름 이 표시 하 는 파일 이나 디 렉 터 리 가 존재 하 는 지 테스트 합 니 다.
10
public boolean isDirectory()
이 추상 적 인 경로 이름 이 표시 하 는 파일 이 디 렉 터 리 인지 테스트 합 니 다.
11
public boolean isFile()
이 추상 적 인 경로 이름 이 표시 하 는 파일 이 표준 파일 인지 테스트 합 니 다.
12
public long lastModified()
이 추상 적 인 경로 이름 으로 표 시 된 파일 이 마지막 으로 수 정 된 시간 을 되 돌려 줍 니 다.
13
public long length()
추상 적 인 경로 이름 으로 표 시 된 파일 의 길 이 를 되 돌려 줍 니 다.
14
public boolean createNewFile() throws IOException
이 추상 적 인 경로 이름 이 지정 한 이름 을 가 진 파일 이 존재 하지 않 을 때 이 추상 적 인 경로 이름 으로 지정 한 새로운 빈 파일 을 원자 적 으로 만 듭 니 다.
15
public boolean delete()
이 추상 적 인 경로 이름 이 표시 하 는 파일 이나 디 렉 터 리 를 삭제 합 니 다.
16
public void deleteOnExit()
가상 컴퓨터 가 종 료 될 때 이 추상 적 인 경로 이름 이 표시 하 는 파일 이나 디 렉 터 리 를 삭제 해 달라 고 요청 합 니 다.
17
public String[] list()
이 추상 적 인 경로 이름 으로 표 시 된 디 렉 터 리 의 파일 과 디 렉 터 리 의 이름 으로 구 성 된 문자열 배열 을 되 돌려 줍 니 다.
18
public String[] list(FilenameFilter filter)
디 렉 터 리 에 포 함 된 파일 과 디 렉 터 리 의 이름 으로 구 성 된 문자열 배열 을 되 돌려 줍 니 다. 이 디 렉 터 리 는 지정 한 필 터 를 만족 시 키 는 추상 적 인 경로 이름 을 통 해 표 시 됩 니 다.
19
public File[] listFiles()
추상 적 인 경로 이름 배열 을 되 돌려 줍 니 다. 이 경로 이름 들 은 이 추상 적 인 경로 이름 이 디 렉 터 리 에 있 는 파일 을 표시 합 니 다.
20
public File[] listFiles(FileFilter filter)
이 추상 적 인 경로 이름 이 디 렉 터 리 에 있 는 파일 과 디 렉 터 리 를 나타 내 는 추상 적 인 경로 이름 배열 을 되 돌려 줍 니 다. 이 경로 이름 들 은 특정한 필 터 를 만족 시 킵 니 다.
21
public boolean mkdir()
이 추상 적 인 경로 이름 이 지정 한 디 렉 터 리 를 만 듭 니 다.
22
public boolean mkdirs()
이 추상 적 인 경로 이름 이 지정 한 디 렉 터 리 를 만 듭 니 다. 필요 하지만 존재 하지 않 는 부모 디 렉 터 리 를 만 드 는 것 을 포함 합 니 다.
23
public boolean renameTo(File dest)
이 추상 적 인 경로 이름 이 표시 하 는 파일 의 이름 을 바 꿉 니 다.
24
public boolean setLastModified(long time)
이 추상 적 인 경로 이름 으로 지정 한 파일 이나 디 렉 터 리 의 마지막 수정 시간 을 설정 합 니 다.
25
public boolean setReadOnly()
이 추상 적 인 경로 이름 이 지정 한 파일 이나 디 렉 터 리 를 표시 하여 읽 기 동작 만 할 수 있 도록 합 니 다.
26
public static File createTempFile(String prefix, String suffix, File directory) throws IOException
지정 한 디 렉 터 리 에 새 빈 파일 을 만 들 고 주어진 접두사 와 접두사 문자열 로 이름 을 만 듭 니 다.
27
public static File createTempFile(String prefix, String suffix) throws IOException
기본 임시 파일 디 렉 터 리 에 빈 파일 을 만 들 고 주어진 접두사 와 접 두 사 를 사용 하여 이름 을 만 듭 니 다.
28
public int compareTo(File pathname)
알파벳 순 으로 두 추상 적 인 경로 명 을 비교 하 다.
29
public int compareTo(Object o)
알파벳 순 으로 추상 적 인 경로 이름과 주어진 대상 을 비교 합 니 다.
30
public boolean equals(Object obj)
이 추상 적 인 경로 이름과 주어진 대상 이 같 는 지 시험 합 니 다.
31
public String toString()
이 추상 적 인 경로 이름 의 경로 이름 문자열 을 되 돌려 줍 니 다.
InputStream 바이트 입력 흐름
package com.gaoji.io;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
//
public class IOdome_03 {
// InputStream
public static void main(String[] args) throws IOException {
File f1 = new File("D://");//
File f2 = new File(f1, "aaa.txt");//
InputStream in =null;
try {
in = new FileInputStream(f2);//
int a = 0;//
// in.skip(1);// n
//
// while ((a=in.read())!=-1) {
// System.out.print((char)a);
// }
// ( , )
byte[] bs = new byte[in.available()];
while ((a=in.read())!=-1) {
for(int i=0;i<bs.length;i++){
if(bs[i]==0){
break;
}
}
System.out.print((char)a);
}
} catch (Exception e) {
e.printStackTrace();
} finally{
in.close();
}
}
}
출력 스 트림 바이트 출력 흐름
package com.gaoji.io;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
//
public class IOdome_04 {
// OutputStream
public static void main(String[] args) throws IOException {
File f1 = new File("D://");//
File f2 = new File(f1, "aaa.txt");//
OutputStream out=null;
try {
out=new FileOutputStream(f2,true);//true ,false
String a="holle wrold1";
//
// byte[] bs=a.getBytes();
// for (int i = 0; i < bs.length; i++) {
// out.write(bs[i]);
// }
//
out.write(a.getBytes());
} catch (Exception e) {
// TODO: handle exception
}finally {
out.flush();// ( , )
out.close();//
}
}
}
리더 문자 입력 흐름
//
public static void reader() {
try {
InputStreamReader fr=new InputStreamReader(new FileInputStream(new File("D:\\aaa.txt")),"utf-8");
char[] cs=new char[6];
fr.read(cs);
System.out.println(new String(cs));
System.out.println(fr.getEncoding());
fr.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Writer 문자 출력 흐름
바이트 출력 흐름 을 사용 하면 파일 흐름 을 새로 고치 지 않 고 시스템 이 자동 으로 새로 고침 되 며 문자 출력 흐름 이 다 릅 니 다. 새로 고침 하지 않 고 닫 으 면 파일 이 작 동 하지 않 습 니 다.
//
public static void writer() {
OutputStreamWriter ows = null;
try {
ows = new OutputStreamWriter(new FileOutputStream(new File("D://aaa.txt")), "gbk");
String a = " ";
ows.write(a);
System.out.println(ows.getEncoding());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
ows.flush();
ows.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
직렬 화 와 반 직렬 화
package com.gaoji.io;
import java.io.Serializable;
//IO Serializable
public class User implements Serializable {
/**
* id
* transient //
*/
private static final long serialVersionUID = 4950216177746797393L;
private int id;
private String name;
private char sex;
private transient String phone;
public User(int id, String name, char sex, String phone) {
super();
this.id = id;
this.name = name;
this.sex = sex;
this.phone = phone;
}
public User() {
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public char getSex() {
return sex;
}
public void setSex(char sex) {
this.sex = sex;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", sex=" + sex + ", phone=" + phone + "]";
}
}
package com.gaoji.io;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
//
public class IOdome_07 {
public static void main(String[] args) throws IOException, ClassNotFoundException {
xlh();
fxlh();
}
//
public static void xlh() throws FileNotFoundException, IOException {
User u = new User(1, " ", ' ', "15665620000");
ObjectOutputStream out = null;
try {
out = new ObjectOutputStream(new FileOutputStream(new File("d:\\user.dat")));
out.writeObject(u);
System.out.println(u);
} finally {
out.flush();//
out.close();//
}
}
//
public static void fxlh() throws IOException, ClassNotFoundException {
ObjectInputStream in = null;
try {
in = new ObjectInputStream(new FileInputStream(new File("d:\\user.dat")));
User u = (User) in.readObject();
System.out.println(u.toString());
} finally {
in.close();
}
}
}
파일 흐름 복사
// FileInputStream FileOutputStream
public static void InputOutputStream() throws IOException {
File f1 = new File("D://");
File f2 = new File(f1, "qqq.jpg");
File f3 = new File("C://");
File f4 = new File(f3, "qqq.jpg");
FileInputStream fis = new FileInputStream(f2);// ( )
FileOutputStream fos = new FileOutputStream(f4);// ( )
int len = 0;
while ((len = fis.read()) != -1) {
fos.write(len);
}
fos.flush();
fos.close();
fis.close();
}
// BufferedInputStream BufferedOutputStream
public static void BufferedInputOutputStream() throws IOException {
// TODO Auto-generated method stub
File f1 = new File("D://");
File f2 = new File(f1, "qqq.jpg");
File f3 = new File("C://");
File f4 = new File(f3, "qqq.jpg");
BufferedInputStream bin = null;
BufferedOutputStream out = null;
try {
byte[] bs = new byte[1024];
bin = new BufferedInputStream(new FileInputStream(f2));
out = new BufferedOutputStream(new FileOutputStream(f4));
while (bin.read(bs) != -1) {
out.write(bs);
}
} catch (Exception e) {
// TODO: handle exception
} finally {
bin.close();
out.flush();
out.close();
}
}
IO 흐름 은 시스템 디스크 의 모든 파일 을 재 귀적 으로 찾 습 니 다.
package com.gaoji.io;
import java.io.File;
public class IOdomemy_01 {
public static void main(String[] args) {
//File f = new File("D://");
File f = new File("D:\\");
//getFile(f);
}
//
public static void getFile(File f) {
File[] fs = f.listFiles();
if(fs != null && fs.length !=0){
for(File f1:fs){
if(f1.isDirectory()){
getFile(f1);
}else{
System.out.println(f1.getName());
}
}
}
}
}
시험 문제 가 공고 하 다.
1. 디스크 루트 디 렉 터 리 에 a. txt 파일 을 새로 만 들 고 파일 에 임의의 내용 을 입력 합 니 다.
package com.gaoji.io;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
//1. d a.txt ,
public class IOword_01 {
public static void main(String[] args) {
dome0111();
}
// createTempFile
public static void dome01(){
File parent=new File("d:"+File.separator);
try {
File file = parent.createTempFile("hjbqq",".txt",parent);
System.out.println(file);
//d:\hjbqq1465893390880583617.txt
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
createNewFile
public static void dome011(){
File f1=new File("d:"+File.separator);
File f2=new File(f1,"txt.txt");
try {
// txt.txt , ,
f2.createNewFile();
System.out.println(" :"+f2.exists());
System.out.println(f2);
//d:\txt.txt
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//
public static void dome0111(){
File f1=new File("d:"+File.separator);
File f2=new File(f1,"txt.txt");
try {
FileWriter fw = new FileWriter(f2);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(" ");
bw.flush();//
bw.close();
fw.close();
System.out.println(" ");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
2. txt. txt 파일 크기 읽 기, 최근 접근 시간, 디 렉 터 리 여부.이 파일 삭제
package com.gaoji.io;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
// txt.txt , , 。
public class IOword_02 {
public static void main(String[] args) {
dome1();
}
public static void dome1() {
File f1 = new File("D:"+File.separator);
File f2 = new File(f1,"txt.txt");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd HH:mm:ss");
System.out.println(f2);
System.out.println(f2+" "+f2.length());
System.out.println(f2+" "+sdf.format(new Date(f2.lastModified())));
System.out.println(f2+" :"+f2.isDirectory());
if(f2.delete()){
System.out.println(" !!");
}else{
System.out.println(" ");
}
}
}
3. 이 폴 더 의 모든 파일 을 삭제 하 는 프로그램 을 만 듭 니 다. (재 귀적 알고리즘 으로 구현)
package com.gaoji.io;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class IOword_03 {
// , ,
// , ( )
public static void main(String[] args) throws IOException {
File f1=new File("d:"+File.separator);
File f2 = new File(f1,"txt");
getFile(f2);
}
//
public static void getFile(File f) {
File[] fs = f.listFiles();
if(fs != null && fs.length !=0){
for(File f1:fs){
if(f1.isDirectory()){
getFile(f1);
}else{
f1.delete();
}
}
}
}
}
자원 다운로드
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
JPA + QueryDSL 계층형 댓글, 대댓글 구현(2)이번엔 전편에 이어서 계층형 댓글, 대댓글을 다시 리팩토링해볼 예정이다. 이전 게시글에서는 계층형 댓글, 대댓글을 구현은 되었지만 N+1 문제가 있었다. 이번에는 그 N+1 문제를 해결해 볼 것이다. 위의 로직은 이...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.