将文件传递给另一个方法时发生异常 [英] Contradicting exceptions when passing file to another method

查看:79
本文介绍了将文件传递给另一个方法时发生异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图将文件传递给另一个以String作为参数的方法,但是在编译时会遇到矛盾的异常。

I'm trying to pass a file to another method which takes a String as its argument, but when I compile it I get contradicting exceptions.

'm调用是:

public static String sortThis(String inputFileName) 
{
//code here
}

我调用该方法的代码是:

The code where I'm calling the method is:

tempFile1 = Sort2.sortThis(tempFile2.getPath());

我得到一个例外:

incompatible types
Found: java.lang.String
Required: java.io.File

因此,如果我只是传递文件:

So if I just pass the file:

tempFile1 = Sort2.sortThis(tempFile2);

我得到:

sortThis(java.lang.String) in Sort2 cannot be applied to (java.io.File)

我使用了错误的File方法来获取文件名/路径吗?我不确定getAbsolutePath(),getCanonicalPath()和getPath()之间有什么区别,所以这可能是它行为异常的原因吗?

Am I using the wrong method of File to get the file name/path? I'm not sure what the difference is between getAbsolutePath(), getCanonicalPath(), and getPath(), so that could be the reason it's acting strangely?

推荐答案

我假设您的 tempFile1 的类型为 File 而不是 String

I'm assuming your tempFile1 is of type File instead of String

下面的编译和工作。

import java.io.File;

public class Test
{
    public static void main( String args[] )
    {
        File file = new File( "" );
        String tempFile1 = Test.sortThis( file.getPath() );
        System.out.println( tempFile1 );
    }

    public static String sortThis( String inputFileName )
    {
        return inputFileName;
    }
}

这篇关于将文件传递给另一个方法时发生异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆