java.io.FileNotFoundException:<my path =“”>(系统找不到指定的文件)。请指导</my>

时间:2014-05-31 08:46:36

标签: java

以下是抛出异常的代码:

java.io.FileNotFoundException: C:\cloud project\Resource freeing attacks in cloud performance code and db\Ftp\Ftp\src\public.key (The system cannot find the file specified)    

我无法弄清楚为什么找不到密钥文件。我怀疑密钥文件没有被写入,这就是系统找不到它们的原因。

package com.util;

import java.net.*;
import java.io.*;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.spec.SecretKeySpec;

public class SimpleFTPClient {
public static String path = "C:/cloud project/Resource freeing attacks in cloud performance code and db/Ftp/Ftp/src/";

private URLConnection m_client;
private String host;
private String user;
private String password;
private String remoteFile;
private String erMesg;
private String succMesg;

public SimpleFTPClient() {
}
public void setHost(String host) {
    this.host = host;
}
public void setUser(String user) {
    this.user = user;
}
public void setPassword(String p) {
    this.password = p;
}

public void setRemoteFile(String d) {
    this.remoteFile = d;
}
public synchronized String getLastSuccessMessage() {
    if (succMesg == null) {
        return "";
    }
    return succMesg;
}
public synchronized String getLastErrorMessage() {
    if (erMesg == null) {
        return "";
    }
    return erMesg;
}
public synchronized boolean uploadFile(InputStream is) {
try {

        BufferedInputStream bis = new BufferedInputStream(is);
        OutputStream os = m_client.getOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(os);
        String algo = "RSA/ECB/PKCS5Padding";
        SimpleFTPClient sftpcx = new SimpleFTPClient();
        KeyPair kpr = sftpcx.LoadKeyPair(path, algo);
        PublicKey pubkey = kpr.getPublic();
        Cipher encrypt =  Cipher.getInstance(algo);  
        encrypt.init(Cipher.ENCRYPT_MODE, pubkey);  
        CipherOutputStream cout=new CipherOutputStream(bos, encrypt);

        byte[] buffer = new byte[1024];
        int readCount;

        while ((readCount = bis.read(buffer)) != -1) {
            cout.write(buffer, 0, readCount);//cout instead of bos
        }
        cout.close();
        bis.close();
        bos.flush();
        bos.close();

        this.succMesg = "Uploaded!";

        return true;
    } catch (Exception ex) {
        ex.printStackTrace();
        StringWriter sw0 = new StringWriter();
        PrintWriter p0 = new PrintWriter(sw0, true);
        ex.printStackTrace(p0);
        erMesg = sw0.getBuffer().toString();

        return false;
    }
}
public synchronized boolean downloadFile(String localfilename) {
    try {
        InputStream is = m_client.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        System.out.println(">>>>>>>>>>>"+localfilename);
        OutputStream os = new FileOutputStream(localfilename);
        BufferedOutputStream bos = new BufferedOutputStream(os);
        String algo = "RSA/ECB/PKCS5Padding";
        SimpleFTPClient sftpc = new SimpleFTPClient();
        KeyPair kpr = sftpc.LoadKeyPair(path, algo);
        PrivateKey prvkey = kpr.getPrivate();
        Cipher decrypt =  Cipher.getInstance(algo);  
        decrypt.init(Cipher.DECRYPT_MODE, prvkey);  
        CipherInputStream cin=new CipherInputStream(bis, decrypt);
        byte[] buffer = new byte[1024];
        int readCount;
        while ((readCount = cin.read(buffer)) != -1) {
            bos.write(buffer, 0, readCount);
        }
        cin.close();
        bis.close();
        bos.flush();
        bos.close();
        this.succMesg = "Downloaded!";

        return true;
    } catch (Exception ex) {
        ex.printStackTrace();
        StringWriter sw0 = new StringWriter();
        PrintWriter p0 = new PrintWriter(sw0, true);
        ex.printStackTrace(p0);
        erMesg = sw0.getBuffer().toString();

        return false;
    }
}

public synchronized boolean connect() {
    try {
        URL url = new URL("ftp://" + user + ":" + password + "@" + host + "/" + remoteFile + ";type=i");
        m_client = url.openConnection();
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>.."+"ftp://" + user + ":" + password + "@" + host + "/" + remoteFile + ";type=i");
        return true;

    } catch (Exception ex) {
        ex.printStackTrace();
        StringWriter sw0 = new StringWriter();
        PrintWriter p0 = new PrintWriter(sw0, true);
        ex.printStackTrace(p0);
        erMesg = sw0.getBuffer().toString();
        return false;
    }
}

public static void main(String arg[]) throws NoSuchAlgorithmException, IOException, InvalidKeySpecException {
    SimpleFTPClient f = new SimpleFTPClient();
    f.setHost("ftp.drivehq.com");
    f.setUser("sabari06");
    f.setPassword("sabari06");
    f.setRemoteFile("c.txt");
    boolean connected = f.connect();
    try{
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(1024);
        KeyPair generatedKeyPair = keyGen.genKeyPair();
    System.out.println("Generated Key Pair");
        f.dumpKeyPair(generatedKeyPair);
    f.SaveKeyPair(path, generatedKeyPair);
    KeyPair loadedKeyPair = f.LoadKeyPair(path, "RSA");
        System.out.println("Loaded Key Pair");
    f.dumpKeyPair(loadedKeyPair);
    }catch (Exception e) {
e.printStackTrace();
return;
}
}
private void dumpKeyPair(KeyPair keyPair) {
    PublicKey pub = keyPair.getPublic();
    System.out.println("Public Key: " + getHexString(pub.getEncoded()));
    PrivateKey priv = keyPair.getPrivate();
    System.out.println("Private Key: " + getHexString(priv.getEncoded()));
}

private String getHexString(byte[] b) {
    String result = "";
    for (int i = 0; i < b.length; i++) {
        result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
    }
    return result;
}

public void SaveKeyPair(String path, KeyPair keyPair) throws IOException {
    PrivateKey privateKey = keyPair.getPrivate();
    PublicKey publicKey = keyPair.getPublic();

    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(
            publicKey.getEncoded());
    FileOutputStream fos = new FileOutputStream(path + "\\public.key");
    fos.write(x509EncodedKeySpec.getEncoded());
    fos.close();

    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(
            privateKey.getEncoded());
    fos = new FileOutputStream(path + "\\private.key");
    fos.write(pkcs8EncodedKeySpec.getEncoded());
    fos.close();
}

 public KeyPair LoadKeyPair(String path, String algorithm)
        throws IOException, NoSuchAlgorithmException,
        InvalidKeySpecException {

    File filePublicKey = new File(path + "/public.key");
    FileInputStream fis = new FileInputStream(path + "/public.key");
    byte[] encodedPublicKey = new byte[(int) filePublicKey.length()];
    fis.read(encodedPublicKey);
    fis.close();

    File filePrivateKey = new File(path + "/private.key");
    fis = new FileInputStream(path + "/private.key");
    byte[] encodedPrivateKey = new byte[(int) filePrivateKey.length()];
    fis.read(encodedPrivateKey);
    fis.close();

    KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
    X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(
            encodedPublicKey);
    PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

    PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(
            encodedPrivateKey);
    PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);

    return new KeyPair(publicKey, privateKey);
}
}

3 个答案:

答案 0 :(得分:1)

管理员的身份打开命令提示符或IDE。根据我的判断,你没有适当的写作权。只需右键单击命令提示符或IDE,然后选择以管理员身份运行并再次尝试执行该程序。

答案 1 :(得分:0)

您的路径包含未转义的空格。对于Windows机器,路径应该类似于

C:\\Users\\Joe\\image.jpg

作为第一步,验证您是否可以从没有空格的文件夹加载文件。例如,将文件移至c:\\temp\\public.key

如果可行,您将知道没有所有权问题或写入权限。 如果这不起作用,那么还有其他事情正在发生。

一旦你能够从c:\ temp加载文件,将文件移回到你想要的位置并处理空格。 要在Windows中转义空格,请使用“/”。例如。 “Program Files”可以引用为c:\ Program / Files \

另外,请记住,您并不总是需要通过绝对名称引用该文件,如果该文件位于类路径中,您可以将其作为资源加载:

InputStream inputStream = YourClass.class.getResourceAsStream("public.key");

最后,尽量不要在文件名中使用平台相关分隔符。而是使用File.separator,File.separatorChar或System.getProperty(“file.separator”)。

答案 2 :(得分:0)

如下面的函数所示,有一个更好的错误消息会有所帮助。 或者通过Windows资源管理器中的路径。

不需要bos.flush,关闭bos包裹。

已经知道并再次确认:在Windows下,正斜杠/是旧的POSIX兼容性功能,所以没关系。反斜杠必须自我转义为\\

创建文件时也可能抛出FileNotFoundException。还要检查文件是否被锁定,可能是被遗忘的close()

上一个解决方案:

file.getParentFile().mkdirs();

检查功能:

/**
 * Throws a FileNotFoundException with the exact spot where the path goes
 * wrong.
 * @param file or directory.
 * @throws FileNotFoundException when not found.
 */
public static void checkFileFound(File file) throws FileNotFoundException {
    if (file.exists()) {
        File firstWrong = file;
        File dir = file.getParentFile();
        while (dir != null && !dir.exists()) {
            firstWrong = dir;
            dir = dir.getParentFile();
        }
        throw new FileNotFoundException("File/Directory does not exist; '"
                + firstWrong.getPath() + "'; in " + file.getPath());
    }
}

uploadFile之后的try {

checkFileNotFound(new File(path));

或制作自己的测试应用:

public static void main(String[] args) {
    try {
        String path = "C:/cloud project/Resource freeing attacks in cloud performance code and db/Ftp/Ftp/src/";
        checkFileNotFound(new File(path));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}