手机实现查看java文件路径_java读写文件以及通过路径查看路径下所有文件夹或文件,...

list=new LinkedList<>();

//考虑到会打成jar包发布 new File()不能使用改用FileSystemResource

File file =new FileSystemResource(path).getFile();

// 获取路径下的所有文件及文件夹

File[] files = file.listFiles();

for (int i = 0; i < files.length; i++) {

// 如果还是文件夹 递归获取里面的文件 文件夹

if (files[i].isDirectory()) {

list.add(files[i].getPath());

list.addAll(getFilesPath(files[i].getPath()));

}

}

return list;

}

/**

* 获取path下的所有文件名列表

* @param path

* @return

*/

public static LinkedList getSheelList(String path) {

LinkedListlist=new LinkedList<>();

File file = new FileSystemResource(path).getFile();

// 获取路径下的所有文件

File[] files = file.listFiles();

if(file==null){

return null;

}

for (int i = 0; i < files.length; i++) {

// 添加文件,非文件夹

if (!files[i].isDirectory()) {

list.add(files[i].getPath());

}

}

return list;

}

/**

* 将内容写进去

* @param path

* @param text

* @return

* @throws IOException

*/

public static Boolean write(String path,String text) throws IOException {

File file = new FileSystemResource(path).getFile();

OutputStream outPutStream = null;

try{

outPutStream = new FileOutputStream(file);

StringBuilder stringBuilder = new StringBuilder();//使用长度可变的字符串对象;

stringBuilder.append(text);//追加文件内容

String context = stringBuilder.toString();//将可变字符串变为固定长度的字符串,方便下面的转码;

byte[] bytes = context.getBytes("UTF-8");//因为中文可能会乱码,这里使用了转码,转成UTF-8;

outPutStream.write(bytes);//开始写入内容到文件;

return true;

}catch(Exception e){

e.printStackTrace();//获取异常

return false;

}finally {

if (outPutStream != null) {

try {

outPutStream.close();

} catch (IOException e1) {

e1.printStackTrace();

}

}

}

}

/**

* 根据路径读取文件内容

* @param fileName

* @return

*/

public static String read(String fileName) {

File file = new FileSystemResource(fileName).getFile();

BufferedReader reader = null;

StringBuffer sbf = new StringBuffer();

try {

reader = new BufferedReader(new FileReader(file));

String tempStr;

while ((tempStr = reader.readLine()) != null) {

sbf.append(tempStr);

sbf.append("\r\n"); //为了解决换行问题

}

reader.close();

return sbf.toString();

} catch (IOException e) {

e.printStackTrace();

} finally {

if (reader != null) {

try {

reader.close();

} catch (IOException e1) {

e1.printStackTrace();

}

}

}

return sbf.toString();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值