Tho*_*mas 3 java junit spring nio maven
问题
我想用Java7s NIO在java中编写数据导入.用户以String形式输入文件的路径,程序尝试使用Paths打开它.当它想要读取它的DosFileAttributes时,会发生java.nio.file.NoSuchFileException:file.txt.
我发现了什么
我发现的唯一答案是使用资源Stream - 但这种接缝不实用,因为要加载的文件是由用户提供的,不应该是jar的一部分.还是我错过了理解?http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResourceAsStream%28java.lang.String%29
我得到了什么
设置:
项目结构:
加载文件的源:
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.DosFileAttributes;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Component;
@Component( "fileLoader" )
public class BufferdFileLoader
implements FileLoader {
@Override
public List<String> loadFile( String path )
throws IOException {
if ( path == null || path.length() == 0 ) {
throw new IllegalArgumentException( "path should not be null" );
}
Path file = Paths.get( path );
// here the Exception is thrown
DosFileAttributes attrs = Files.readAttributes( file, DosFileAttributes.class );
if ( !attrs.isRegularFile() ) {
throw new IOException( "could not read file, invalid path" );
}
List<String> result = new ArrayList<String>();
try (BufferedReader reader = Files.newBufferedReader( file, Charset.forName( "UTF-8" ) )) {
String line = null;
while ( ( line = reader.readLine() ) != null ) {
result.add( line );
}
}
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
测试案例很简单:
import java.io.IOException;
import java.util.List;
import javax.inject.Inject;
import lombok.Setter;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* Class under test {@link BufferdFileLoader}
*
*/
@ContextConfiguration
public class BufferdFileLoaderTest
extends AbstractTestNGSpringContextTests {
/**
* Class under test
*/
@Inject
@Setter
private BufferdFileLoader bufferdFileLoader;
/**
* Method under test {@link BufferdFileLoader#loadFile(String)}
*
* @throws IOException
*/
@Test( groups = { "integration" }, enabled = true )
public void testImportFeedsFromXMLFileWitEmptyXml()
throws IOException {
String filename = "empty-example-takeout.xml";
List<String> list = this.bufferdFileLoader.loadFile( filename );
Assert.assertEquals( list.size(), 0 );
}
}
Run Code Online (Sandbox Code Playgroud)
所以我的问题是
如何使用NIO加载文件,以便可以使用maven测试,也可以在生产环境中使用?
mik*_*łak 14
好吧,这是在Path测试的类路径中为您测试资源的正确问题.
编辑:这更简洁:
Paths.get(getClass().getResource("/"+filename).toURI()).toString()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7603 次 |
| 最近记录: |