java判断文件是否在磁盘中存在
时间: 2023-12-09 22:03:24 浏览: 38
在Java中,我们可以使用`java.io.File`类来判断文件是否存在。可以使用该类的`exists()`方法来检查文件是否存在。以下是示例代码:
```java
import java.io.File;
public class FileExistenceChecker {
public static void main(String[] args) {
String filePath = "C:\\Users\\username\\Desktop\\example.txt";
File file = new File(filePath);
if(file.exists()) {
System.out.println("File exists in the disk!");
} else {
System.out.println("File does not exist in the disk!");
}
}
}
```
在上面的代码中,我们首先创建一个`File`对象,然后使用`exists()`方法来检查文件是否存在。如果文件存在,则打印消息“File exists in the disk!”,否则打印消息“File does not exist in the disk!”。请注意,文件路径中使用的反斜杠字符“\”需要用双反斜杠“\\”来转义。
相关问题
java中文件上传的后端代码
以下是一个简单的Java文件上传的后端代码示例:
```java
import java.io.File;
import java.io.IOException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class FileUploadController {
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
// 判断文件是否为空
if (file.isEmpty()) {
return "上传文件为空";
}
try {
// 获取文件名和扩展名
String fileName = file.getOriginalFilename();
String extension = fileName.substring(fileName.lastIndexOf(".") + 1);
// 将文件保存到本地磁盘
file.transferTo(new File("/path/to/save/file/" + fileName));
return "文件上传成功!";
} catch (IOException e) {
e.printStackTrace();
return "文件上传失败:" + e.getMessage();
}
}
}
```
在上面的代码中,我们使用了Spring MVC框架,通过使用`@PostMapping`注解将一个POST请求映射到`/upload`路径上。在方法中,我们使用`@RequestParam`注解来接收上传的文件,然后判断文件是否为空,获取文件名和扩展名,并将文件保存到本地磁盘。最后返回一个成功或失败的消息。
java中文件上传下载的代码及注释
文件上传代码及注释如下:
```java
import java.io.File;
import java.io.IOException;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class FileController {
@Value("${file.upload.path}")
private String uploadPath; // 上传文件的路径,从配置文件中读取
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) { // 判断上传的文件是否为空
return "redirect:/error";
}
// 生成一个唯一的文件名
String fileName = UUID.randomUUID().toString() + "-" + file.getOriginalFilename();
File destFile = new File(uploadPath + "/" + fileName);
try {
file.transferTo(destFile); // 将文件保存到磁盘中
return "redirect:/success";
} catch (IOException e) {
e.printStackTrace();
return "redirect:/error";
}
}
}
```
文件上传的主要逻辑是通过 `MultipartFile` 类型的参数来接收上传的文件,然后将其保存到指定的路径中。
文件下载代码及注释如下:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@Controller
public class FileController {
@Value("${file.upload.path}")
private String uploadPath; // 上传文件的路径,从配置文件中读取
@GetMapping("/download/{fileName:.+}")
public void downloadFile(@PathVariable("fileName") String fileName, HttpServletResponse response) {
File file = new File(uploadPath + "/" + fileName);
if (!file.exists()) { // 判断文件是否存在
return;
}
try (FileInputStream inputStream = new FileInputStream(file);
OutputStream outputStream = response.getOutputStream()) {
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
byte[] buffer = new byte[4096];
int length;
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
文件下载的主要逻辑是通过 `HttpServletResponse` 类型的参数来向客户端输出文件。在输出文件之前,需要设置响应头,包括内容类型和文件名。然后读取文件内容并写入输出流中即可。