从/ src / main / resources /读取文件

时间:2014-12-30 10:15:43

标签: java eclipse web path relative

您好我正在尝试使用Web应用程序并遇到问题: 我不知道如何使用保存在资源文件夹中的Java打开文本文件:

text file saved in the resource folder

 String relativeWebPath ="/src/main/resources/words.txt";  //Import der des Textdoumentes
 String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
 File f = new File(absoluteDiskPath);

(文件words.txt)

正如您在图像上看到的,我正在尝试访问words.txt,但它无法正常工作。有什么想法吗?

4 个答案:

答案 0 :(得分:6)

试试这个。

InputStream is = getClass().getClassLoader()
                         .getResourceAsStream("/words.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(is));

答案 1 :(得分:0)

为了获得最佳实践并避免这些问题,请将文本文件(words.txt)放入WEB_INF文件夹(这是资源的安全文件夹)。然后:

ServletContext context = getContext();
InputStream resourceContent = context.getResourceAsStream("/WEB-INF/words.txt");

参考:https://stackoverflow.com/a/4342095/3728901

答案 2 :(得分:0)

使用此代码查找您要打开的文件的路径。

namespace App\Admin;

use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use App\Entity\Website;

class AttributeAdmin extends AbstractAdmin
{
private $attribute;

//public function __construct(Attribute $attribute){
    //parent::__construct();
    //$this->attribute = $attribute;
//}

protected function configureFormFields(FormMapper $formMapper)
{
    $formMapper->add('slug', TextType::class);
    $formMapper->add('name', TextType::class);
    $formMapper->add('website', EntityType::class, array(
'class'    => 'App\Entity\Website',
'multiple' => true)
);
}

protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
    $datagridMapper->add('slug');
    $datagridMapper->add('name');
}

protected function configureListFields(ListMapper $listMapper)
{
    $listMapper->addIdentifier('slug');
    $listMapper->addIdentifier('name');
    $listMapper->add('created_at', 'datetime', array('format' => 'Y-m-d H:m:s'));
    $listMapper->add('updated_at','datetime', array('format' => 'Y-m-d H:m:s'));
}
}

答案 3 :(得分:0)

如果您要访问其他类,例如您有一个实用程序包,并且其中有一个ReadFileUtil.java类可以打开并读取文件,则可以通过以下方式进行操作:

public class ReadFileUtil {

        URL url = ReadFileUtil.class.getResource("/"+yourFileName);
        File file = new File(url.getPath());

    }