最近因为公司需求,需要java读取windows上的设备共享文件夹,但是最后代码需要放在linux上面。所以出现了在windows上面开发的代码不生效的问题。最后通过在linux上面挂载windows的共享文件夹后,重新编写读取程序,从而实现功能。在网上查找相关资料,但是都不是很全面,现在把相关代码分享,希望能帮到大家!
依赖如下:
<dependencies>
<dependency>
<groupId>org.samba.jcifs</groupId>
<artifactId>jcifs</artifactId>
<version>1.3.3</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.2</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.6.1</version>
</dependency>
</dependencies>
1、读取windows下的共享文件夹下的所有文件
@Resource
private MaterialsService materialsService;
@Resource
private PurchaseOrderService purchaseOrderService;
private static String USER_DOMAIN = "";
private static String USER_ACCOUNT = "Equator";
private static String USER_PWS = "equator";
private static String SOURCE_URL = "smb://192.168.20.160/SQLBinaryData0140/gong_xiang_bao_gao/";
private static String TARGET_URL = "\\\\192.168.20.160\\SQLBinaryData0140\\ExamineItemByTestingEquipmentBak\\";
* @Title listFiles
* @Description 遍历指定目录下的文件(共享文件夹)
* @author Created by Chen Yang
* @date 2021-07-19
public void listFiles(String shareDirectory) throws Exception {
long startTime = System.currentTimeMillis();
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(USER_DOMAIN, USER_ACCOUNT, USER_PWS);
SmbFile remoteFile = new SmbFile(shareDirectory, auth);
if (remoteFile.exists()) {
SmbFile[] files = remoteFile.listFiles();
for (SmbFile f : files) {
if(f.getName().indexOf(".txt") > -1 || f.getName().indexOf(".TXT") > -1 ){
File file = new File(f.getUncPath());
ArrayList<ExamineByTestingEquipment> testCardItemMapList = txt2String(file);
if(CollUtil.isNotEmpty(testCardItemMapList)){
this.insertBatch(testCardItemMapList);
File targetFile = new File(new String((TARGET_URL+f.getName().toString()).getBytes("utf-8"),"utf-8"));
boolean result = removeFile(file,targetFile);
if (!result) {
throw new CswRuntimeException("文件移动失败!");
} else {
throw new CswRuntimeException("目录下无文件!");
2、读取linux下的共享文件夹的所有文件
@Resource
private MaterialsService materialsService;
@Resource
private PurchaseOrderService purchaseOrderService;
private static String USER_DOMAIN = "";
private static String USER_ACCOUNT = "Equator";
private static String USER_PWS = "equator";
private static String SOURCE_URL = "/share/gong_xiang_bao_gao/";
private static String TARGET_URL = "/share/ExamineItemByTestingEquipmentBak/";
* @Title queryLinuxFileNames
* @Description 遍历指定目录下的文件(LNIUX下)
* @author Created by Chen Yang
* @date 2021-07-19
public void queryLinuxFileNames(String path) throws Exception {
File linuxFile=new File(path);
if(linuxFile.exists()){
File[] tempList = linuxFile.listFiles();
System.out.println("该目录下对象个数:"+tempList.length);
for(File f: tempList){
if(f.getName().indexOf(".txt") > -1 || f.getName().indexOf(".TXT") > -1 ){
File file = new File(f.toString());
ArrayList<ExamineByTestingEquipment> testCardItemMapList = txt2String(file);
if(CollUtil.isNotEmpty(testCardItemMapList)){
this.insertBatch(testCardItemMapList);
File targetFile = new File(TARGET_URL+f.getName().toString());
boolean result = removeFile2(file,targetFile);
if (!result) {
System.out.println("文件移动失败!");
}else{
System.out.println("目录下无文件!");
3、实现文件的读取
* 读取txt文件的内容
* @param file 想要读取的文件对象
* @author Created by Chen Yang
* @return 返回文件内容
public ArrayList<ExamineByTestingEquipment> txt2String(File file){
ArrayList<ExamineByTestingEquipment> testCardItemMapList = new ArrayList<ExamineByTestingEquipment>();
String testCardItemnum = null;
String itemCode = null;
String poOrder = null;
boolean flag = false;
try{
BufferedReader br = new BufferedReader(new FileReader(file));
String s = null;
int i = 0;
ExamineByTestingEquipment examineByTestingEquipment;
Materials materials;
PurchaseOrder purchaseOrder;
while((s = br.readLine())!=null){
if(flag && s.indexOf("#") == -1){
if((s.split("\\s+").length > 1 && s.indexOf("TruePosition2D") > -1) ||
(s.split("\\s+").length > 1 && s.indexOf("Perpendicular") > -1)){
examineByTestingEquipment = new ExamineByTestingEquipment();
materials = new Materials();
purchaseOrder = new PurchaseOrder();
materials.setCode(itemCode);
purchaseOrder.setCode(poOrder);
if(materialsService.getMaterials(materials) == null || purchaseOrderService.getPurchaseOrder(purchaseOrder) == null ){
continue;
examineByTestingEquipment.setId(IdWorker.getId());
examineByTestingEquipment.setMaterials(materials);
examineByTestingEquipment.setMaterialsId(materialsService.getMaterials(materials).getId());
examineByTestingEquipment.setPurchaseOrder(purchaseOrder);
examineByTestingEquipment.setPurchaseOrderId(purchaseOrderService.getPurchaseOrder(purchaseOrder).getId());
examineByTestingEquipment.setExamineNum(Integer.parseInt(testCardItemnum));
examineByTestingEquipment.setExamineName(s.split("\\s+")[0]);
examineByTestingEquipment.setExamineValue(s.split("\\s+")[1]);
examineByTestingEquipment.setVersion(examineByTestingEquipment.getVersion());
examineByTestingEquipment.setCreateUser("admin");
examineByTestingEquipment.setCreateUserId(Long.parseLong("1196980511038091266"));
examineByTestingEquipment.setGmtCreate(new Date());
examineByTestingEquipment.setModifiedUser("admin");
examineByTestingEquipment.setGmtModified(new Date());
testCardItemMapList.add(examineByTestingEquipment);
}else{
flag = false;
if (s.indexOf("#") > -1 && !flag){
flag = true;
testCardItemnum = s.substring(1);
if(i == 5){
itemCode = s.trim();
if(i == 6){
poOrder = s.trim();
i += 1;
br.close();
}catch(Exception e){
e.printStackTrace();
return testCardItemMapList;
4、将已经读取过的文件放到另一个目录下
方法1:
* 移动文件到另一个目录
public boolean removeFile(File sourceFile, File targetFile){
boolean result = sourceFile.renameTo(targetFile);
return result;
* 移动文件到另一个目录
public boolean removeFile2(File sourceFile, File targetFile){
boolean result = false;
FileInputStream in = null;
FileOutputStream out = null;
try {
BufferedReader br = new BufferedReader(new FileReader(sourceFile));
BufferedWriter bw = new BufferedWriter(new FileWriter(targetFile));
String s = null;
while((s = br.readLine())!=null){
bw.write(s);
bw.newLine();
bw.close();
br.close();
if (sourceFile.exists() && targetFile.exists()) {
result = sourceFile.delete();
} catch (IOException e) {
e.printStackTrace();
return result;
关于java读取LINUX目录、文件及读取windows共享文件夹的详细方法最近因为公司需求,需要java读取windows上的设备共享文件夹,但是最后代码需要放在linux上面。所以出现了在windows上面开发的代码不生效的问题。最后通过在linux上面挂载windows的共享文件夹后,重新编写读取程序,从而实现功能。在网上查找相关资料,但是都不是很全面,现在把相关代码分享,希望能帮到大家!依赖如下:<dependencies> <dependency>
windows中文件路径用 \ 表示,Linux中文件路径用 / 表示;
Java中提供了一个与平台无关的表示路径的常量 File.separator,如:String strFile=File.separator+"opt"+File.separator+"note.txt";//表示绝对路径 /opt/note.txt
2.权限问题
读取的文件要是可读的,chmod 77
ClassPathResource cpr = new ClassPathResource("templates/szjcbg.docx");
URL url = cpr.getURL();
String inputUrl = url.getPath();
Java获取linux系统文件(注意反斜杠!)
String inputUrl ="/work/software/szjcbg.d
import ch.ethz.ssh2.ChannelCondition;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.StreamGobbler;
要在Java中读取Linux本地文件,可以使用Java IO类库中的FileInputStream和BufferedReader类。以下是一个简单的示例代码:
```java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class ReadFileExample {
public static void main(String[] args) {
try {
File file = new File("/path/to/file.txt"); // 文件路径
FileInputStream fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
br.close();
fis.close();
} catch (Exception e) {
e.printStackTrace();
在上面的代码中,我们首先创建一个File对象,指定要读取的文件路径。然后使用FileInputStream类创建一个输入流对象,将其传递给BufferedReader类的构造函数中,以便逐行读取文件内容。最后,我们使用while循环读取文件中的每一行,并将其打印到控制台上。
请注意,要读取Linux本地文件,需要在Java程序中使用Linux文件系统的路径格式,例如“/path/to/file.txt”。