Как я могу получить файл, включенный в мою исходную директорию? - PullRequest
8 голосов
/ 20 декабря 2011

У меня довольно простой макет каталога для моего проекта Maven / Eclipse:

.
├── pom.xml
└── src
    ├── main
    │   ├── java
    │   │   ├── org
    │   │   │   └── tkassembled
    │   │   │       └── maven
    │   │   │           └── jasperreports
    │   │   │               └── JasperReportsApplication.java
    │   │   └── sampleReport.xml
    │   └── resources
    └── test
        ├── java
        └── resources

11 directories, 3 files

Как видите, у меня есть файл sampleReport.xml в базе исходного каталога Java, но когда я пытаюсь открыть его, я получаю FileNotFoundException:

Exception in thread "main" java.io.FileNotFoundException: sampleReport.xml (No such file or directory)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.java:137)
    at org.tkassembled.maven.jasperreports.JasperReportsApplication.main(JasperReportsApplication.java:34)

Вот мой pom.xml:

<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" 
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <groupId>org.tkassembled.maven</groupId>
    <artifactId>jasperreports-test</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>JasperReports Testing</name>

    <dependencies>
        <!-- SLF4J -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.6.4</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>log4j-over-slf4j</artifactId>
            <version>1.6.4</version>
        </dependency>
        <!-- Logback -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <version>1.0.0</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.0.0</version>
        </dependency>
        <!-- JasperReports -->
        <dependency>
            <groupId>jasperreports</groupId>
            <artifactId>jasperreports</artifactId>
            <version>3.5.3</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

А вот мое Java-приложение:

package org.tkassembled.maven.jasperreports;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.net.URI;
import java.net.URL;

import net.sf.jasperreports.engine.JasperCompileManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JasperReportsApplication {

    private static final Logger logger = LoggerFactory.getLogger(JasperReportsApplication.class);

    /*
     * There are basically four steps to a finished product:
     *      <X> Design a report with a JRXML file.
     *      <X> Compile the report to a binary, serialized JasperReport and save to disk.
     *      <X> Fill the compiled report with data.
     *      <X> Export it.
     */
    public static void main(String[] args) throws Exception {
        File jrxml = new File("sampleReport.xml");
//      URL url = JasperReportsApplication.class.getResource("sampleReport.xml");
//      File jrxml = new File(url.getFile());
        assert jrxml.exists();
        assert jrxml.isFile();

        File compileTarget = File.createTempFile("output", "jasper");

        FileInputStream jrxmlInput = new FileInputStream(jrxml);
        FileInputStream jasperInput = new FileInputStream(compileTarget);
        FileOutputStream jasperOutput = new FileOutputStream(compileTarget);

//      compile the report
        JasperCompileManager.compileReportToStream(jrxmlInput, jasperOutput);

//      lol

    }
}

Как мне найти этот файл в корне моего исходного каталога?

Ответы [ 3 ]

11 голосов
/ 20 декабря 2011

Когда Maven упаковывает его, он помещает его в .jar проекта, он больше не будет доступен как File.

Доступен как Stream с

    JasperReportsApplication.class.getResourceAsStream("/sampleReport.xml")

Этот файл должен фактически находиться в каталоге src/main/resources вместо каталога src/main/java, чтобы следовать соглашениям Maven, то есть это не исходный код Java.

1 голос
/ 20 декабря 2011

Не исходные файлы должны по умолчанию находиться в папке src / main / resources.

0 голосов
/ 20 декабря 2011

Вы захотите включить этот файл в свою папку ресурсов (по умолчанию в src / main / resources ). Вы также можете изменить местоположение по умолчанию .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...