java操作文件
获取项目路径
在linux常用方式
String path = Cz.class.getResource("").getPath();
//在cmd或linux里执行的结果为
path=file:/E:/cz/qbsea.jar!/com/qbsea/cz/
//处理截取path
String path = "file:/E:/cz/qbsea.jar!/com/qbsea/cz/";
path = path.substring(0, path.indexOf("!"));
path = path.substring(0, path.lastIndexOf("/"));
path = path.replaceAll("file:", "");
//最终的结果为 /E:/cz
在idea常用方式
path=/C:/myprogram/merge/maqingbin/master/mytest/mytest-simple/target/classes/com/qbsea/cz/
path=path.substring(0,path.lastIndexOf("/target"));
//最终的结果为 /C:/myprogram/merge/maqingbin/master/mytest/mytest-simple
测试结果
无"/"
String path = Cz.class.getResource("").getPath();
在idea里执行后的路径为
path=/C:/myprogram/merge/maqingbin/master/mytest/mytest-simple/target/classes/com/qbsea/cz/
在cmd或linux命令行执行的路径为
path=file:/E:/cz/qbsea.jar!/com/qbsea/cz/
有"/"
String path = Cz.class.getResource("/").getPath();
在idea里执行的路径为
path=/C:/myprogram/merge/maqingbin/master/mytest/mytest-simple/target/classes/
在cmd里或linux里执行的路径为
Exception in thread "main" java.lang.NullPointerException
at com.qbsea.cz.Cz.main(Cz.java:20)
Cz.class.getResource("/") 得到一个NULL
读文件
字节流-FileInputStream
纯字节流
File f = new File("E:"+File.separator+"java2"+File.separator+"StreamDemo"+File.separator+"test.txt");
InputStream in = new FileInputStream(f);
byte b[]=new byte[(int)f.length()]; //创建合适文件大小的数组
in.read(b); //读取文件中的内容到b[]数组
in.close();
System.out.println(new String(b));
比如你读到文件是GBK的内容,而你输出的文件为UTF-8则要显示的转一下
读字节流使用字节数组做缓冲
字节流转字符流
BufferedReader–>InputStreamReader–>InputStream
ServletInputStream inputStream = request.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(inputStream));
StringBuffer sb = new StringBuffer();
String str = null;
while((str = br.readLine())!=null){
sb.append(str);
}
//然后用这个sb.toString()来处理逻辑
字符流-FileReader
FileReader reader = new FileReader(path);
BufferedReader br = new BufferedReader(reader);
StringBuffer sb = new StringBuffer();
String str = null;
while((str=br.readLine()) !=null){
sb.append(str).append("\n");
}
reader.close();
读jar包中的文件
普通
InputStream is = Xxxx.class.getResourceAsStream("/xxx/xxx.xml")//类路径下
spring-ResourceLoader
ResourceLoader读取classpath:目录下的文件
import org.springframework.core.io.ResourceLoader;
implements ResourceLoaderAware
@Setter
private ResourceLoader resourceLoader;
Resource resource = resourceLoader.getResource("classpath:/myfile/test.xml");
resource.getInputStream();
ResourcePatternResolver读取classpath*:目录下的文件
classpath*表示能够将jar包下的文件能够读出来
@Setter
private ResourcePatternResolver resourceLoader;
private InputStream getInputStream(String xmlPath) {
//先走相对路径
try {
Resource[] resources = resourceLoader.getResources(xmlPath);
return resources[0].getInputStream();
}catch(Fi1eNotFoundException e) {//再走绝对路径
try {
FileInputStream fileInputStream = new FileInputStream xmlPath) ;
return fileInput Stream;
}catch(FileNotFoundException e1) {
logger.error(String. format("%s通过resour ceLoader在resources目录下没有找到,同时在绝对路径下也未能找到”,xmlPath), e1);
}
}catch(I0Exception e){
logger.error(xmlPath+" is error",e);
throw new RuntimeException(e);
}
return null;
}
例子
package com.qbsea.mysboot2shirojwt.test.resource;
import lombok.Getter;
import lombok.Setter;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import retrofit2.http.GET;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@Getter
@Setter
public class ResourceTest implements ResourceLoaderAware {
private ResourceLoader resourceLoader;
@Test
public void test() {
Resource resource = resourceLoader.getResource("classpath:/myfile/test.xml");
try (
InputStreamReader reader = new InputStreamReader(resource.getInputStream());
BufferedReader br = new BufferedReader(reader);
) {
StringBuffer sb = new StringBuffer();
String str = null;
while ((str = br.readLine()) != null) {
sb.append(str).append("\n");
}
System.out.println(sb.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
写文件
BufferedWriter能够指定文件编码
使用该字符流写文件,可以指定文件的编码格式 如图所示
File file = new File(targetPath);
FileOutputStream writerStream = new FileOutputStream(file);
//指定文件的编码格式
BufferedWriter fileWriter = new BufferedWriter(new OutputStreamWriter(writerStream,"UTF-8"));
fileWriter.write(sql);
ByteArrayOutputStream|ByteArrayInputStream
将一个文件写到字节数组
FileInputStream inputStream = new FileInputStream(path) ;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int length = 0;
while ((length = inputStream. read(buf)) != -1) {
baos.write(buf, off: 0, length);
}
byte[] byteFile = baos.toByteArray() ;
将序列化对象写到字节数组
public byte[] getObjectSerializeBytes(object paramSerilation){//入参是序列化对象
if(paramSerilation ==null){
return null;
}
byte[] bytes=null;
try (ByteArrayOutputStream bos= new ByteArrayOutputStream();
ObjectOutputStream oos= new ObjectOutputStream(bos)){
//通过序列化输出流将数据打到ByteArrayOutputStream里
oos.writeObject(paramSerilation);
oos.flush();
bytes=bos.toByteArray();
}catch(IOException e){
//
}
return bytes;
}
ByteArrayOutputStream
ByteArrayOutputStream baos = cloneInputStream(input);
byte[] byteArray = baos.toByteArray();
//将字节数组转成一个新的输入流
InputStream stream1 = new ByteArrayInputStream(baos.toByteArray());
字符流
String path = "/xx/xx/filepath";
File file = new File(path);
if(!file.exists()){
file.createNewFile();
}
FileWriter writer = new FileWriter(file);
writer.write(xxxxString);
writer.close();
输出压缩包
FileOutputStream fOutputStream = new FileOutputStream(file);
ZipOutputStream zoutput = new ZipOutputStream(fOutputStream);
ZipEntry zEntry = new ZipEntry(xxxzipRoot根目录文件名xxx);
zoutput.putNextEntry(zEntry);
zoutput.write(xxx具体的内容byte[]xxx);
zoutput.closeEntry();
zoutput.close();
强制刷盘
// 关键是下面这句,强制将数据写入磁盘
FileDescriptor fd = fos.getFD();
fd.sync();
判断文件内容编码格式的工具类
点击 具体的参考类连接
java.nio.file
public class Main {
public static void main(String[] args) throws IOException {
String targetFilePath = "d:/1.txt";//目标文件
FileInputStream fileInputStream = new FileInputStream(new File("d:/source.txt"));
//判断文件是否存在
boolean pathExists = Files.exists(Paths.get(targetFilePath), new LinkOption[]{LinkOption.NOFOLLOW_LINKS});
if (!pathExists) {//如果不存在
//创建上层文件目录
Path directories = Files.createDirectories(Paths.get(targetFilePath.substring(0, targetFilePath.lastIndexOf("/"))));
//创建文件
Path path = Files.createFile(Paths.get(targetFilePath));
}
//将source.txt文件中去 拷贝到 1.txt文件中去 StandardCopyOption.REPLACE_EXISTING表示以前文件有内容直接覆盖掉
Files.copy(fileInputStream,Paths.get(targetFilePath), StandardCopyOption.REPLACE_EXISTING);
}
}