在gs上将Java1.8Lambdas转换为Java1.7上载文件Spring引导示例
我正在做一些关于弹簧靴的练习 通过示例,当我使用Java8时,它工作得很好,但不幸的是,我在web服务中包装的代码需要Java7。我已经列出了所有的错误代码,有人能帮我将lambdas转换成1.7兼容的代码,并替换新的库(java.util.stream.stream和java.util.stream.collector) Application.java在gs上将Java1.8Lambdas转换为Java1.7上载文件Spring引导示例,java,spring,spring-boot,lambda,Java,Spring,Spring Boot,Lambda,我正在做一些关于弹簧靴的练习 通过示例,当我使用Java8时,它工作得很好,但不幸的是,我在web服务中包装的代码需要Java7。我已经列出了所有的错误代码,有人能帮我将lambdas转换成1.7兼容的代码,并替换新的库(java.util.stream.stream和java.util.stream.collector) Application.java @SpringBootApplication @EnableConfigurationProperties(StoragePropertie
@SpringBootApplication
@EnableConfigurationProperties(StorageProperties.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
CommandLineRunner init(StorageService storageService) {
return (args) -> {
storageService.deleteAll();
storageService.init();
};
}
}
import java.util.stream.Collectors
//..
@GetMapping("/")
public String listUploadedFiles(Model model) throws IOException {
model.addAttribute("files", storageService
.loadAll()
.map(path ->
MvcUriComponentsBuilder
.fromMethodName(FileUploadController.class, "serveFile", path.getFileName().toString())
.build().toString())
.collect(Collectors.toList()));
return "uploadForm";
}
@Override
public Stream<Path> loadAll() {
try {
return Files.walk(this.rootLocation, 1)
.filter(path -> !path.equals(this.rootLocation))
.map(path -> this.rootLocation.relativize(path));
} catch (IOException e) {
throw new StorageException("Failed to read stored files", e);
}
}
import java.util.stream.Stream;
public interface StorageService {
void init();
void store(MultipartFile file);
Stream<Path> loadAll();
Path load(String filename);
Resource loadAsResource(String filename);
void deleteAll();
}
@SpringBootApplication
@EnableConfigurationProperties(StorageProperties.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
CommandLineRunner init(StorageService storageService) {
return new CommandLineRunner() {
@Override
public void run(String... args) throws Exception {
storageService.deleteAll();
storageService.init();
}
};
}
}
@GetMapping("/")
public String listUploadedFiles(Model model) throws IOException {
List<Path> paths = storageService.loadAll();
List<String> sPaths = new ArrayList<>(paths.size());
for (Path path : paths) {
sPaths.add(MvcUriComponentsBuilder
.fromMethodName(FileUploadController.class, "serveFile", path.getFileName().toString())
.build().toString());
}
model.addAttribute("files", sPaths);
return "uploadForm";
}
@Override
public List<Path> loadAll() {
List<Path> rPaths = new ArrayList<>();
try (DirectoryStream<Path> stream = Files.newDirectoryStream(this.rootLocation)) {
for (Path entry: stream) {
rPaths.add(rootLocation.relativize(entry));
}
} catch (IOException e) {
throw new StorageException("Failed to read stored files", e);
}
return rPaths;
}
public interface StorageService {
void init();
void store(MultipartFile file);
List<Path> loadAll();
Path load(String filename);
Resource loadAsResource(String filename);
void deleteAll();
}
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java8.util.Spliterator;
import java8.util.Spliterators;
import java8.util.function.Function;
import java8.util.function.Predicate;
import java8.util.stream.Stream;
import java8.util.stream.StreamSupport;
public class FileSystemStorageService implements StorageService {
@Override
public Stream<Path> loadAll() {
try {
final DirectoryStream<Path> ds = Files.newDirectoryStream(rootLocation);
return StreamSupport
.stream(Spliterators.spliteratorUnknownSize(
ds.iterator(), Spliterator.DISTINCT), false)
.onClose(new Runnable() {
@Override
public void run() {
try {
ds.close();
} catch (IOException e) {
throw new StorageException(
"Failed to close stream", e);
}
}
})
.filter(new Predicate<Path>() {
@Override
public boolean test(Path path) {
return !path.equals(rootLocation);
}
}).map(new Function<Path, Path>() {
@Override
public Path apply(Path path) {
return rootLocation.relativize(path);
}
});
} catch (IOException e) {
throw new StorageException("Failed to read stored files", e);
}
}
}
import java.io.IOException;
import java.nio.file.Path;
import java8.util.function.Function;
import java8.util.stream.Collectors;
import java8.util.stream.Stream;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
public class FileUploadController {
@GetMapping("/")
public String listUploadedFiles(Model model) throws IOException {
Stream<Path> stream = null;
try {
stream = storageService.loadAll();
model.addAttribute("files",
stream.map(new Function<Path, String>() {
public String apply(Path path) {
return MvcUriComponentsBuilder
.fromMethodName(FileUploadController.class,
"serveFile",
path.getFileName().toString()).build()
.toString();
}
}).collect(Collectors.toList()));
} finally {
if (stream != null) {
stream.close();
}
}
return "uploadForm";
}
}
return(args)->错误提示“使用source-8或更高版本启用
lambda表达式”
FileUploadController.java
@SpringBootApplication
@EnableConfigurationProperties(StorageProperties.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
CommandLineRunner init(StorageService storageService) {
return (args) -> {
storageService.deleteAll();
storageService.init();
};
}
}
import java.util.stream.Collectors
//..
@GetMapping("/")
public String listUploadedFiles(Model model) throws IOException {
model.addAttribute("files", storageService
.loadAll()
.map(path ->
MvcUriComponentsBuilder
.fromMethodName(FileUploadController.class, "serveFile", path.getFileName().toString())
.build().toString())
.collect(Collectors.toList()));
return "uploadForm";
}
@Override
public Stream<Path> loadAll() {
try {
return Files.walk(this.rootLocation, 1)
.filter(path -> !path.equals(this.rootLocation))
.map(path -> this.rootLocation.relativize(path));
} catch (IOException e) {
throw new StorageException("Failed to read stored files", e);
}
}
import java.util.stream.Stream;
public interface StorageService {
void init();
void store(MultipartFile file);
Stream<Path> loadAll();
Path load(String filename);
Resource loadAsResource(String filename);
void deleteAll();
}
@SpringBootApplication
@EnableConfigurationProperties(StorageProperties.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
CommandLineRunner init(StorageService storageService) {
return new CommandLineRunner() {
@Override
public void run(String... args) throws Exception {
storageService.deleteAll();
storageService.init();
}
};
}
}
@GetMapping("/")
public String listUploadedFiles(Model model) throws IOException {
List<Path> paths = storageService.loadAll();
List<String> sPaths = new ArrayList<>(paths.size());
for (Path path : paths) {
sPaths.add(MvcUriComponentsBuilder
.fromMethodName(FileUploadController.class, "serveFile", path.getFileName().toString())
.build().toString());
}
model.addAttribute("files", sPaths);
return "uploadForm";
}
@Override
public List<Path> loadAll() {
List<Path> rPaths = new ArrayList<>();
try (DirectoryStream<Path> stream = Files.newDirectoryStream(this.rootLocation)) {
for (Path entry: stream) {
rPaths.add(rootLocation.relativize(entry));
}
} catch (IOException e) {
throw new StorageException("Failed to read stored files", e);
}
return rPaths;
}
public interface StorageService {
void init();
void store(MultipartFile file);
List<Path> loadAll();
Path load(String filename);
Resource loadAsResource(String filename);
void deleteAll();
}
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java8.util.Spliterator;
import java8.util.Spliterators;
import java8.util.function.Function;
import java8.util.function.Predicate;
import java8.util.stream.Stream;
import java8.util.stream.StreamSupport;
public class FileSystemStorageService implements StorageService {
@Override
public Stream<Path> loadAll() {
try {
final DirectoryStream<Path> ds = Files.newDirectoryStream(rootLocation);
return StreamSupport
.stream(Spliterators.spliteratorUnknownSize(
ds.iterator(), Spliterator.DISTINCT), false)
.onClose(new Runnable() {
@Override
public void run() {
try {
ds.close();
} catch (IOException e) {
throw new StorageException(
"Failed to close stream", e);
}
}
})
.filter(new Predicate<Path>() {
@Override
public boolean test(Path path) {
return !path.equals(rootLocation);
}
}).map(new Function<Path, Path>() {
@Override
public Path apply(Path path) {
return rootLocation.relativize(path);
}
});
} catch (IOException e) {
throw new StorageException("Failed to read stored files", e);
}
}
}
import java.io.IOException;
import java.nio.file.Path;
import java8.util.function.Function;
import java8.util.stream.Collectors;
import java8.util.stream.Stream;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
public class FileUploadController {
@GetMapping("/")
public String listUploadedFiles(Model model) throws IOException {
Stream<Path> stream = null;
try {
stream = storageService.loadAll();
model.addAttribute("files",
stream.map(new Function<Path, String>() {
public String apply(Path path) {
return MvcUriComponentsBuilder
.fromMethodName(FileUploadController.class,
"serveFile",
path.getFileName().toString()).build()
.toString();
}
}).collect(Collectors.toList()));
} finally {
if (stream != null) {
stream.close();
}
}
return "uploadForm";
}
}
包java.util.stream不存在
类型loadAll()错误
“使用源代码-8或更高版本启用
lambda表达式”
FileSystemStorageService.java
@SpringBootApplication
@EnableConfigurationProperties(StorageProperties.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
CommandLineRunner init(StorageService storageService) {
return (args) -> {
storageService.deleteAll();
storageService.init();
};
}
}
import java.util.stream.Collectors
//..
@GetMapping("/")
public String listUploadedFiles(Model model) throws IOException {
model.addAttribute("files", storageService
.loadAll()
.map(path ->
MvcUriComponentsBuilder
.fromMethodName(FileUploadController.class, "serveFile", path.getFileName().toString())
.build().toString())
.collect(Collectors.toList()));
return "uploadForm";
}
@Override
public Stream<Path> loadAll() {
try {
return Files.walk(this.rootLocation, 1)
.filter(path -> !path.equals(this.rootLocation))
.map(path -> this.rootLocation.relativize(path));
} catch (IOException e) {
throw new StorageException("Failed to read stored files", e);
}
}
import java.util.stream.Stream;
public interface StorageService {
void init();
void store(MultipartFile file);
Stream<Path> loadAll();
Path load(String filename);
Resource loadAsResource(String filename);
void deleteAll();
}
@SpringBootApplication
@EnableConfigurationProperties(StorageProperties.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
CommandLineRunner init(StorageService storageService) {
return new CommandLineRunner() {
@Override
public void run(String... args) throws Exception {
storageService.deleteAll();
storageService.init();
}
};
}
}
@GetMapping("/")
public String listUploadedFiles(Model model) throws IOException {
List<Path> paths = storageService.loadAll();
List<String> sPaths = new ArrayList<>(paths.size());
for (Path path : paths) {
sPaths.add(MvcUriComponentsBuilder
.fromMethodName(FileUploadController.class, "serveFile", path.getFileName().toString())
.build().toString());
}
model.addAttribute("files", sPaths);
return "uploadForm";
}
@Override
public List<Path> loadAll() {
List<Path> rPaths = new ArrayList<>();
try (DirectoryStream<Path> stream = Files.newDirectoryStream(this.rootLocation)) {
for (Path entry: stream) {
rPaths.add(rootLocation.relativize(entry));
}
} catch (IOException e) {
throw new StorageException("Failed to read stored files", e);
}
return rPaths;
}
public interface StorageService {
void init();
void store(MultipartFile file);
List<Path> loadAll();
Path load(String filename);
Resource loadAsResource(String filename);
void deleteAll();
}
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java8.util.Spliterator;
import java8.util.Spliterators;
import java8.util.function.Function;
import java8.util.function.Predicate;
import java8.util.stream.Stream;
import java8.util.stream.StreamSupport;
public class FileSystemStorageService implements StorageService {
@Override
public Stream<Path> loadAll() {
try {
final DirectoryStream<Path> ds = Files.newDirectoryStream(rootLocation);
return StreamSupport
.stream(Spliterators.spliteratorUnknownSize(
ds.iterator(), Spliterator.DISTINCT), false)
.onClose(new Runnable() {
@Override
public void run() {
try {
ds.close();
} catch (IOException e) {
throw new StorageException(
"Failed to close stream", e);
}
}
})
.filter(new Predicate<Path>() {
@Override
public boolean test(Path path) {
return !path.equals(rootLocation);
}
}).map(new Function<Path, Path>() {
@Override
public Path apply(Path path) {
return rootLocation.relativize(path);
}
});
} catch (IOException e) {
throw new StorageException("Failed to read stored files", e);
}
}
}
import java.io.IOException;
import java.nio.file.Path;
import java8.util.function.Function;
import java8.util.stream.Collectors;
import java8.util.stream.Stream;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
public class FileUploadController {
@GetMapping("/")
public String listUploadedFiles(Model model) throws IOException {
Stream<Path> stream = null;
try {
stream = storageService.loadAll();
model.addAttribute("files",
stream.map(new Function<Path, String>() {
public String apply(Path path) {
return MvcUriComponentsBuilder
.fromMethodName(FileUploadController.class,
"serveFile",
path.getFileName().toString()).build()
.toString();
}
}).collect(Collectors.toList()));
} finally {
if (stream != null) {
stream.close();
}
}
return "uploadForm";
}
}
@覆盖
公共流loadAll(){
试一试{
return Files.walk(this.rootLocation,1)
.filter(path->!path.equals(this.rootLocation))
.map(path->this.rootLocation.relativize(path));
}捕获(IOE异常){
抛出新的StorageException(“读取存储文件失败”,e);
}
}
找不到符号漫游
“使用源代码-8或更高版本启用
lambda表达式”
StorageService.java
@SpringBootApplication
@EnableConfigurationProperties(StorageProperties.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
CommandLineRunner init(StorageService storageService) {
return (args) -> {
storageService.deleteAll();
storageService.init();
};
}
}
import java.util.stream.Collectors
//..
@GetMapping("/")
public String listUploadedFiles(Model model) throws IOException {
model.addAttribute("files", storageService
.loadAll()
.map(path ->
MvcUriComponentsBuilder
.fromMethodName(FileUploadController.class, "serveFile", path.getFileName().toString())
.build().toString())
.collect(Collectors.toList()));
return "uploadForm";
}
@Override
public Stream<Path> loadAll() {
try {
return Files.walk(this.rootLocation, 1)
.filter(path -> !path.equals(this.rootLocation))
.map(path -> this.rootLocation.relativize(path));
} catch (IOException e) {
throw new StorageException("Failed to read stored files", e);
}
}
import java.util.stream.Stream;
public interface StorageService {
void init();
void store(MultipartFile file);
Stream<Path> loadAll();
Path load(String filename);
Resource loadAsResource(String filename);
void deleteAll();
}
@SpringBootApplication
@EnableConfigurationProperties(StorageProperties.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
CommandLineRunner init(StorageService storageService) {
return new CommandLineRunner() {
@Override
public void run(String... args) throws Exception {
storageService.deleteAll();
storageService.init();
}
};
}
}
@GetMapping("/")
public String listUploadedFiles(Model model) throws IOException {
List<Path> paths = storageService.loadAll();
List<String> sPaths = new ArrayList<>(paths.size());
for (Path path : paths) {
sPaths.add(MvcUriComponentsBuilder
.fromMethodName(FileUploadController.class, "serveFile", path.getFileName().toString())
.build().toString());
}
model.addAttribute("files", sPaths);
return "uploadForm";
}
@Override
public List<Path> loadAll() {
List<Path> rPaths = new ArrayList<>();
try (DirectoryStream<Path> stream = Files.newDirectoryStream(this.rootLocation)) {
for (Path entry: stream) {
rPaths.add(rootLocation.relativize(entry));
}
} catch (IOException e) {
throw new StorageException("Failed to read stored files", e);
}
return rPaths;
}
public interface StorageService {
void init();
void store(MultipartFile file);
List<Path> loadAll();
Path load(String filename);
Resource loadAsResource(String filename);
void deleteAll();
}
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java8.util.Spliterator;
import java8.util.Spliterators;
import java8.util.function.Function;
import java8.util.function.Predicate;
import java8.util.stream.Stream;
import java8.util.stream.StreamSupport;
public class FileSystemStorageService implements StorageService {
@Override
public Stream<Path> loadAll() {
try {
final DirectoryStream<Path> ds = Files.newDirectoryStream(rootLocation);
return StreamSupport
.stream(Spliterators.spliteratorUnknownSize(
ds.iterator(), Spliterator.DISTINCT), false)
.onClose(new Runnable() {
@Override
public void run() {
try {
ds.close();
} catch (IOException e) {
throw new StorageException(
"Failed to close stream", e);
}
}
})
.filter(new Predicate<Path>() {
@Override
public boolean test(Path path) {
return !path.equals(rootLocation);
}
}).map(new Function<Path, Path>() {
@Override
public Path apply(Path path) {
return rootLocation.relativize(path);
}
});
} catch (IOException e) {
throw new StorageException("Failed to read stored files", e);
}
}
}
import java.io.IOException;
import java.nio.file.Path;
import java8.util.function.Function;
import java8.util.stream.Collectors;
import java8.util.stream.Stream;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
public class FileUploadController {
@GetMapping("/")
public String listUploadedFiles(Model model) throws IOException {
Stream<Path> stream = null;
try {
stream = storageService.loadAll();
model.addAttribute("files",
stream.map(new Function<Path, String>() {
public String apply(Path path) {
return MvcUriComponentsBuilder
.fromMethodName(FileUploadController.class,
"serveFile",
path.getFileName().toString()).build()
.toString();
}
}).collect(Collectors.toList()));
} finally {
if (stream != null) {
stream.close();
}
}
return "uploadForm";
}
}
import java.util.stream.stream;
公共接口存储服务{
void init();
无效存储(多部分文件);
流加载全部();
路径加载(字符串文件名);
资源loadAsResource(字符串文件名);
void deleteAll();
}
包java.util.stream不存在
lambda实际上是单方法接口,称为函数接口。只需遵循IDE代码的完整性,就可以轻松地将大多数lambda表达式转换为接口。例如,让我们采用一个过滤方法:
filter(Predicate<? super T> predicate)
您可以轻松地创建自己的谓词实现,并在迭代示例时使用它。例如,您可以创建自己的泛型过滤器
方法,该方法采用集合
和将应用于每个元素的谓词策略。您还可以使用GuavaFunction
接口,这些接口在Java8之前就已经使用过了。这里有一些关于如何使用它的说明:
总而言之,你可以使用番石榴或为每个例子制作你自己的包装。您可以通过迭代集合来模拟流。转换lambdas是一件很容易的事,因为您知道它们只是单一方法接口。Bulltorious,我很抱歉您的慷慨,但您确实只有很少的选择。流API仅在Java8中添加,因此在Java7中不存在。您可以通过手动编写匿名类,甚至几乎自动地解决与lambda相关的问题(请参阅)。但是,对于流API,您只有两种选择:
文件。行走
)
如果您的文件.walk
是您唯一使用Java-8特定API的地方,您可以相对轻松地将其替换为Java 7 API:
接口路径名映射器
{
字符串映射路径(路径);
}
列表loadAll(路径名映射器映射器)
{
尝试
{
列表结果=新建ArrayList();
Files.walkFileTree(rootLocation,EnumSet.noneOf(FileVisitOption.class),1,新的SimpleFileVisitor()
{
@凌驾
公共文件VisitResult visitFile(路径文件,基本文件属性属性属性)引发IOException
{
如果(!rootLocation.equals(文件))
{
add(mapper.mapPath(rootLocation.relatiize(file));
}
返回FileVisitResult.CONTINUE;
}
});
返回结果;
}
捕获(IOE异常)
{
抛出新的StorageException(“读取存储文件失败”,e);
}
}
然后您的列表上载文件将变成
@GetMapping(“/”)
公共字符串listUploadedFiles(模型)引发IOException
{
model.addAttribute(“文件”),storageService
.loadAll(新的路径名映射器()
{
@凌驾
公共字符串映射路径(路径)
{
返回组件生成器
.fromMethodName(FileUploadController.class,“serveFile”,path.getFileName().toString())
.build().toString();
}
}));
返回“上传表单”;
}
更新2(labmda->匿名类转换)
为了完整起见,举一个如何手动将lambda转换为匿名类的示例:
@Bean
CommandLineRunner初始化(存储服务存储服务)
{
返回新的CommandLineRunner()
{
@凌驾
公共无效运行(字符串…参数)引发异常
{
storageService.deleteAll();
init();
}
};
}
您可以将下面的方法更新为Java 7变体。所有测试用例都通过了
Application.java
@SpringBootApplication
@EnableConfigurationProperties(StorageProperties.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
CommandLineRunner init(StorageService storageService) {
return (args) -> {
storageService.deleteAll();
storageService.init();
};
}
}
import java.util.stream.Collectors
//..
@GetMapping("/")
public String listUploadedFiles(Model model) throws IOException {
model.addAttribute("files", storageService
.loadAll()
.map(path ->
MvcUriComponentsBuilder
.fromMethodName(FileUploadController.class, "serveFile", path.getFileName().toString())
.build().toString())
.collect(Collectors.toList()));
return "uploadForm";
}
@Override
public Stream<Path> loadAll() {
try {
return Files.walk(this.rootLocation, 1)
.filter(path -> !path.equals(this.rootLocation))
.map(path -> this.rootLocation.relativize(path));
} catch (IOException e) {
throw new StorageException("Failed to read stored files", e);
}
}
import java.util.stream.Stream;
public interface StorageService {
void init();
void store(MultipartFile file);
Stream<Path> loadAll();
Path load(String filename);
Resource loadAsResource(String filename);
void deleteAll();
}
@SpringBootApplication
@EnableConfigurationProperties(StorageProperties.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
CommandLineRunner init(StorageService storageService) {
return new CommandLineRunner() {
@Override
public void run(String... args) throws Exception {
storageService.deleteAll();
storageService.init();
}
};
}
}
@GetMapping("/")
public String listUploadedFiles(Model model) throws IOException {
List<Path> paths = storageService.loadAll();
List<String> sPaths = new ArrayList<>(paths.size());
for (Path path : paths) {
sPaths.add(MvcUriComponentsBuilder
.fromMethodName(FileUploadController.class, "serveFile", path.getFileName().toString())
.build().toString());
}
model.addAttribute("files", sPaths);
return "uploadForm";
}
@Override
public List<Path> loadAll() {
List<Path> rPaths = new ArrayList<>();
try (DirectoryStream<Path> stream = Files.newDirectoryStream(this.rootLocation)) {
for (Path entry: stream) {
rPaths.add(rootLocation.relativize(entry));
}
} catch (IOException e) {
throw new StorageException("Failed to read stored files", e);
}
return rPaths;
}
public interface StorageService {
void init();
void store(MultipartFile file);
List<Path> loadAll();
Path load(String filename);
Resource loadAsResource(String filename);
void deleteAll();
}
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java8.util.Spliterator;
import java8.util.Spliterators;
import java8.util.function.Function;
import java8.util.function.Predicate;
import java8.util.stream.Stream;
import java8.util.stream.StreamSupport;
public class FileSystemStorageService implements StorageService {
@Override
public Stream<Path> loadAll() {
try {
final DirectoryStream<Path> ds = Files.newDirectoryStream(rootLocation);
return StreamSupport
.stream(Spliterators.spliteratorUnknownSize(
ds.iterator(), Spliterator.DISTINCT), false)
.onClose(new Runnable() {
@Override
public void run() {
try {
ds.close();
} catch (IOException e) {
throw new StorageException(
"Failed to close stream", e);
}
}
})
.filter(new Predicate<Path>() {
@Override
public boolean test(Path path) {
return !path.equals(rootLocation);
}
}).map(new Function<Path, Path>() {
@Override
public Path apply(Path path) {
return rootLocation.relativize(path);
}
});
} catch (IOException e) {
throw new StorageException("Failed to read stored files", e);
}
}
}
import java.io.IOException;
import java.nio.file.Path;
import java8.util.function.Function;
import java8.util.stream.Collectors;
import java8.util.stream.Stream;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
public class FileUploadController {
@GetMapping("/")
public String listUploadedFiles(Model model) throws IOException {
Stream<Path> stream = null;
try {
stream = storageService.loadAll();
model.addAttribute("files",
stream.map(new Function<Path, String>() {
public String apply(Path path) {
return MvcUriComponentsBuilder
.fromMethodName(FileUploadController.class,
"serveFile",
path.getFileName().toString()).build()
.toString();
}
}).collect(Collectors.toList()));
} finally {
if (stream != null) {
stream.close();
}
}
return "uploadForm";
}
}
FileUploadController.java
@SpringBootApplication
@EnableConfigurationProperties(StorageProperties.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
CommandLineRunner init(StorageService storageService) {
return (args) -> {
storageService.deleteAll();
storageService.init();
};
}
}
import java.util.stream.Collectors
//..
@GetMapping("/")
public String listUploadedFiles(Model model) throws IOException {
model.addAttribute("files", storageService
.loadAll()
.map(path ->
MvcUriComponentsBuilder
.fromMethodName(FileUploadController.class, "serveFile", path.getFileName().toString())
.build().toString())
.collect(Collectors.toList()));
return "uploadForm";
}
@Override
public Stream<Path> loadAll() {
try {
return Files.walk(this.rootLocation, 1)
.filter(path -> !path.equals(this.rootLocation))
.map(path -> this.rootLocation.relativize(path));
} catch (IOException e) {
throw new StorageException("Failed to read stored files", e);
}
}
import java.util.stream.Stream;
public interface StorageService {
void init();
void store(MultipartFile file);
Stream<Path> loadAll();
Path load(String filename);
Resource loadAsResource(String filename);
void deleteAll();
}
@SpringBootApplication
@EnableConfigurationProperties(StorageProperties.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
CommandLineRunner init(StorageService storageService) {
return new CommandLineRunner() {
@Override
public void run(String... args) throws Exception {
storageService.deleteAll();
storageService.init();
}
};
}
}
@GetMapping("/")
public String listUploadedFiles(Model model) throws IOException {
List<Path> paths = storageService.loadAll();
List<String> sPaths = new ArrayList<>(paths.size());
for (Path path : paths) {
sPaths.add(MvcUriComponentsBuilder
.fromMethodName(FileUploadController.class, "serveFile", path.getFileName().toString())
.build().toString());
}
model.addAttribute("files", sPaths);
return "uploadForm";
}
@Override
public List<Path> loadAll() {
List<Path> rPaths = new ArrayList<>();
try (DirectoryStream<Path> stream = Files.newDirectoryStream(this.rootLocation)) {
for (Path entry: stream) {
rPaths.add(rootLocation.relativize(entry));
}
} catch (IOException e) {
throw new StorageException("Failed to read stored files", e);
}
return rPaths;
}
public interface StorageService {
void init();
void store(MultipartFile file);
List<Path> loadAll();
Path load(String filename);
Resource loadAsResource(String filename);
void deleteAll();
}
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java8.util.Spliterator;
import java8.util.Spliterators;
import java8.util.function.Function;
import java8.util.function.Predicate;
import java8.util.stream.Stream;
import java8.util.stream.StreamSupport;
public class FileSystemStorageService implements StorageService {
@Override
public Stream<Path> loadAll() {
try {
final DirectoryStream<Path> ds = Files.newDirectoryStream(rootLocation);
return StreamSupport
.stream(Spliterators.spliteratorUnknownSize(
ds.iterator(), Spliterator.DISTINCT), false)
.onClose(new Runnable() {
@Override
public void run() {
try {
ds.close();
} catch (IOException e) {
throw new StorageException(
"Failed to close stream", e);
}
}
})
.filter(new Predicate<Path>() {
@Override
public boolean test(Path path) {
return !path.equals(rootLocation);
}
}).map(new Function<Path, Path>() {
@Override
public Path apply(Path path) {
return rootLocation.relativize(path);
}
});
} catch (IOException e) {
throw new StorageException("Failed to read stored files", e);
}
}
}
import java.io.IOException;
import java.nio.file.Path;
import java8.util.function.Function;
import java8.util.stream.Collectors;
import java8.util.stream.Stream;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
public class FileUploadController {
@GetMapping("/")
public String listUploadedFiles(Model model) throws IOException {
Stream<Path> stream = null;
try {
stream = storageService.loadAll();
model.addAttribute("files",
stream.map(new Function<Path, String>() {
public String apply(Path path) {
return MvcUriComponentsBuilder
.fromMethodName(FileUploadController.class,
"serveFile",
path.getFileName().toString()).build()
.toString();
}
}).collect(Collectors.toList()));
} finally {
if (stream != null) {
stream.close();
}
}
return "uploadForm";
}
}
StorageService.java
@SpringBootApplication
@EnableConfigurationProperties(StorageProperties.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
CommandLineRunner init(StorageService storageService) {
return (args) -> {
storageService.deleteAll();
storageService.init();
};
}
}
import java.util.stream.Collectors
//..
@GetMapping("/")
public String listUploadedFiles(Model model) throws IOException {
model.addAttribute("files", storageService
.loadAll()
.map(path ->
MvcUriComponentsBuilder
.fromMethodName(FileUploadController.class, "serveFile", path.getFileName().toString())
.build().toString())
.collect(Collectors.toList()));
return "uploadForm";
}
@Override
public Stream<Path> loadAll() {
try {
return Files.walk(this.rootLocation, 1)
.filter(path -> !path.equals(this.rootLocation))
.map(path -> this.rootLocation.relativize(path));
} catch (IOException e) {
throw new StorageException("Failed to read stored files", e);
}
}
import java.util.stream.Stream;
public interface StorageService {
void init();
void store(MultipartFile file);
Stream<Path> loadAll();
Path load(String filename);
Resource loadAsResource(String filename);
void deleteAll();
}
@SpringBootApplication
@EnableConfigurationProperties(StorageProperties.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
CommandLineRunner init(StorageService storageService) {
return new CommandLineRunner() {
@Override
public void run(String... args) throws Exception {
storageService.deleteAll();
storageService.init();
}
};
}
}
@GetMapping("/")
public String listUploadedFiles(Model model) throws IOException {
List<Path> paths = storageService.loadAll();
List<String> sPaths = new ArrayList<>(paths.size());
for (Path path : paths) {
sPaths.add(MvcUriComponentsBuilder
.fromMethodName(FileUploadController.class, "serveFile", path.getFileName().toString())
.build().toString());
}
model.addAttribute("files", sPaths);
return "uploadForm";
}
@Override
public List<Path> loadAll() {
List<Path> rPaths = new ArrayList<>();
try (DirectoryStream<Path> stream = Files.newDirectoryStream(this.rootLocation)) {
for (Path entry: stream) {
rPaths.add(rootLocation.relativize(entry));
}
} catch (IOException e) {
throw new StorageException("Failed to read stored files", e);
}
return rPaths;
}
public interface StorageService {
void init();
void store(MultipartFile file);
List<Path> loadAll();
Path load(String filename);
Resource loadAsResource(String filename);
void deleteAll();
}
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java8.util.Spliterator;
import java8.util.Spliterators;
import java8.util.function.Function;
import java8.util.function.Predicate;
import java8.util.stream.Stream;
import java8.util.stream.StreamSupport;
public class FileSystemStorageService implements StorageService {
@Override
public Stream<Path> loadAll() {
try {
final DirectoryStream<Path> ds = Files.newDirectoryStream(rootLocation);
return StreamSupport
.stream(Spliterators.spliteratorUnknownSize(
ds.iterator(), Spliterator.DISTINCT), false)
.onClose(new Runnable() {
@Override
public void run() {
try {
ds.close();
} catch (IOException e) {
throw new StorageException(
"Failed to close stream", e);
}
}
})
.filter(new Predicate<Path>() {
@Override
public boolean test(Path path) {
return !path.equals(rootLocation);
}
}).map(new Function<Path, Path>() {
@Override
public Path apply(Path path) {
return rootLocation.relativize(path);
}
});
} catch (IOException e) {
throw new StorageException("Failed to read stored files", e);
}
}
}
import java.io.IOException;
import java.nio.file.Path;
import java8.util.function.Function;
import java8.util.stream.Collectors;
import java8.util.stream.Stream;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
public class FileUploadController {
@GetMapping("/")
public String listUploadedFiles(Model model) throws IOException {
Stream<Path> stream = null;
try {
stream = storageService.loadAll();
model.addAttribute("files",
stream.map(new Function<Path, String>() {
public String apply(Path path) {
return MvcUriComponentsBuilder
.fromMethodName(FileUploadController.class,
"serveFile",
path.getFileName().toString()).build()
.toString();
}
}).collect(Collectors.toList()));
} finally {
if (stream != null) {
stream.close();
}
}
return "uploadForm";
}
}
文件系统存储服务测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class FileSystemStorageServiceTest {
@Autowired
private StorageService storageService;
@Test
public void loadAll() throws Exception {
MockMultipartFile multipartFile =
new MockMultipartFile("file", "test.txt", "text/plain", "Spring Framework".getBytes());
storageService.store(multipartFile);
List<Path> paths = storageService.loadAll();
assertThat(paths.size()).isEqualTo(1);
}
}
我添加了两个方法,只是为了测试。一个使用DirectoryStream
,另一个使用WalkFileTree
,并将maxDepth
设置为1。两者的作用相同
@Override
public List<Path> loadAllDirectoryStream() {
List<Path> rPaths = new ArrayList<>();
try (DirectoryStream<Path> stream = Files.newDirectoryStream(this.rootLocation)) {
for (Path entry: stream) {
//if(!Files.isDirectory(entry))
rPaths.add(rootLocation.relativize(entry));
}
} catch (IOException e) {
throw new StorageException("Failed to read stored files", e);
}
return rPaths;
}
@Override
public List<Path> loadAllWalkFileWithDepth1() {
List<Path> rPaths = new ArrayList<>();
try {
Files.walkFileTree(rootLocation, EnumSet.noneOf(FileVisitOption.class), 1, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (!rootLocation.equals(file)) {
rPaths.add(rootLocation.relativize(file));
}
return FileVisitResult.CONTINUE;
}
});
return rPaths;
} catch (IOException e) {
throw new StorageException("Failed to read stored files", e);
}
}
@覆盖
公共列表loadAllDirectoryStream(){
List rpath=new ArrayList();
try(DirectoryStream=Files.newDirectoryStream(this.rootLocation)){
for(路径条目:流){