本帖最后由 够了没有 于 2015-10-30 16:21 编辑
我的项目刚开始是GBK格式编码的,现在想把src文件夹里所有文本文件转成UTF-8编码格式,但是运行却报错了。
错误提示:
java.io.FileNotFoundException: H:\exam\src (拒绝访问。)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at com.itheima.CopyFold_My.copyFile(CopyFold_My.java:56)
at com.itheima.CopyFold_My.copyFolder(CopyFold_My.java:33)
at com.itheima.CopyFold_My.copyFolder(CopyFold_My.java:36)
at com.itheima.CopyFold_My.copyFolder(CopyFold_My.java:36)
at com.itheima.CopyFold_My.main(CopyFold_My.java:19)
为什么会出现这种错误呢?
- package com.itheima;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.OutputStreamWriter;
- public class CopyFold_My
- {
- static String charset;
- static String newFold;
- static String destinationFold = "H:/exam/src/copy";
- static File fileSrc = new File("H:/exam/src");
- public static void main(String[] args)
- {
- copyFolder(fileSrc);
- }
- public static void copyFolder(File fileSrc)
- {
- if (fileSrc.isFile())
- {
- copyFile(fileSrc, new File(destinationFold + File.separator + fileSrc.getName()));
- } else
- {
- File[] listFiles = fileSrc.listFiles();
- for (File file : listFiles)
- {
- if (file.isFile())
- {
- copyFile(file, new File(destinationFold + File.separator + fileSrc.getName() + File.separator + file.getName()));
- } else
- {
- copyFolder(file);
- }
- }
- }
- }
- public static void copyFile(File src, File destination)
- {
- try
- {
- InputStream in = new java.io.FileInputStream(src);
- byte[] b = new byte[3];
- in.read(b);
- in.close();
- if (b[0] == -17 && b[1] == -69 && b[2] == -65)
- {
- charset = "UTF-8";
- } else
- {
- charset = "GBK";
- }
- InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(fileSrc), charset);
- OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(destination), "UTF-8");
- char[] ch = new char[1024];
- while (inputStreamReader.read(ch) != -1)
- {
- outputStreamWriter.write(ch);
- }
- outputStreamWriter.flush();
- outputStreamWriter.close();
- inputStreamReader.close();
- } catch (Exception e)
- {
- e.printStackTrace();
- }
- }
- }
复制代码 |
|