システムは、指定されたファイルを見つけることができませんが、ファイルが存在します

このようなエンジェル:

私はのtest.xmlと呼ばれる私のXMLファイルを操作しようとしています。

私は自分のフォルダ内のファイルを見ることができますし、私はそれを開くことができます。コード:

DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();            
domFactory.setIgnoringComments(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse(new File("MyFolder\Test.xml"));

私はこのエラーを取得しています:

java.io.FileNotFoundException: C:\MyFolder\Test.xml (The system cannot find the file specified)

なぜコードオープン/私のファイルを読み込むことはできませんが、メモ帳++のような他のプログラムには、そうすることができますか?

***注:ファイルの本当の名前は "使用例\ testSuitesA_E_1002 + $ {ユーザー} 3_12022016 + $ {日付} 2_2.5.xml"。

アニッシュB.:

これにあなたのコードを変更してください:

ClassLoader classLoader = ClassLoader.getSystemClassLoader();
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setIgnoringComments(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse(new File(classLoader.getResource("MyFolder/Test.xml").getPath()));
System.out.println(doc.getDocumentElement());

このコードを実行するには、プロジェクトのためのビルド.classファイルを。クラスローダは、持っている必要があります.classファイルを。それ以外の場合は、クラスパスからフォルダやファイルを読み取ることができなくなります。

注意 :

  1. 新しいファイル( "はMyFolder \ Test.xmlを") - This will not work because you have not provided the absolute path. You have to use classloader to get file from classpath (in that case, you don't have to mention the full path). Classloader brings the full absolute path for you. Remember : java.nio.File needs absolute path for its working.

  2. If you want to read file from any arbitrary location, then you have to specify the full path for that.(assuming that you are trying to access the file outside)

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=118009&siteId=1