0
点赞
收藏
分享

微信扫一扫

JAVA中关于文件的读取和写入操作


package test.first;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;

import org.junit.Test;

public class FileTest {

private static String path="d:\\test.txt";

/**
*
* 以字节的方式输入到文件
* @Title: write1
* @date 2016年6月29日 下午3:17:07
* @author 光喜
* @modifier
* @modifydate
*/
@Test
public void write1(){
try {
File f = new File(path);
OutputStream out=new FileOutputStream(f);
out.write("以字节的方式输入到文件".getBytes());
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
* 以字符的方式输入到文件
* @Title: write2
* @date 2016年6月29日 下午3:18:05
* @author 光喜
* @modifier
* @modifydate
*/
@Test
public void write2(){
try {
File f = new File(path);
Writer write=new FileWriter(f);
write.write("以字符的方式输入到文件");
write.close();

} catch (Exception e) {
e.printStackTrace();
}
}

/**
*
* 以字节的方式从文件中读取数据(知道文件的大小)
* @Title: read1
* @date 2016年6月29日 下午3:23:43
* @author 光喜
* @modifier
* @modifydate
*/
@Test
public void read1(){
try {
File f =new File(path);
InputStream in = new FileInputStream(f);
byte[] b =new byte[(int)f.length()];
in.read(b);
in.close();
System.out.println(new String(b));
} catch (Exception e) {
e.printStackTrace();
}
}

/**
*
* 以字节的方式从文件中读取数据(不知道文件的大小)
* @Title: read1
* @date 2016年6月29日 下午3:23:43
* @author 光喜
* @modifier
* @modifydate
*/
@Test
public void read2(){
try {
File f =new File(path);
InputStream in = new FileInputStream(f);
byte[] b =new byte[1024];
int temp=0;
int index=0;
while((temp=in.read())!=-1){
b[index]=(byte)temp;
index++;
}
in.close();
System.out.println(new String(b,0,index));
} catch (Exception e) {
e.printStackTrace();
}
}

/**
*
* 以字符的方式从文件中读取数据
* @Title: write2
* @date 2016年6月29日 下午3:18:05
* @author 光喜
* @modifier
* @modifydate
*/
@Test
public void read3(){
try {
File f = new File(path);
Reader read=new FileReader(f);
char[] c=new char[1024];
int temp=0;
int index=0;
while((temp=read.read())!=-1){
c[index]=(char)temp;
index++;
}
read.close();
System.out.println(new String(c,0,index));

} catch (Exception e) {
e.printStackTrace();
}
}
}



举报

相关推荐

0 条评论