相关文章推荐
心软的钥匙扣  ·  wps ...·  1 年前    · 
儒雅的针织衫  ·  reactjs - support for ...·  1 年前    · 
有胆有识的海龟  ·  How to get height of ...·  1 年前    · 

关于java读取LINUX目录、文件及读取windows共享文件夹的详细方法

最近因为公司需求,需要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);
        //System.out.println("远程共享目录访问耗时:【{}】" + (System.currentTimeMillis() - startTime));
        if (remoteFile.exists()) {
            SmbFile[] files = remoteFile.listFiles();
            //System.out.println("文件存在");
            for (SmbFile f : files) {
                //System.out.println(f.getName());
                if(f.getName().indexOf(".txt") > -1 || f.getName().indexOf(".TXT") > -1 ){
                    File file = new File(f.getUncPath());
                    //System.out.println(f.getUncPath());
                    ArrayList<ExamineByTestingEquipment> testCardItemMapList  = txt2String(file);
                    if(CollUtil.isNotEmpty(testCardItemMapList)){
                        this.insertBatch(testCardItemMapList);
                        //System.out.println(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());
                    //System.out.println(f.getUncPath());
                    ArrayList<ExamineByTestingEquipment> testCardItemMapList  = txt2String(file);
                    if(CollUtil.isNotEmpty(testCardItemMapList)){
                        this.insertBatch(testCardItemMapList);
                        //System.out.println(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));//构造一个BufferedReader类来读取文件 String s = null; int i = 0; ExamineByTestingEquipment examineByTestingEquipment; Materials materials; PurchaseOrder purchaseOrder; while((s = br.readLine())!=null){//使用readLine方法,一次读一行 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(); //System.out.println(testCardItemMapList); 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));//构造一个BufferedReader类来读取文件 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(); //System.out.println(result); return result; 关于java读取LINUX目录、文件及读取windows共享文件夹的详细方法最近因为公司需求,需要java读取windows上的设备共享文件夹,但是最后代码需要放在linux上面。所以出现了在windows上面开发的代码不生效的问题。最后通过在linux上面挂载windows的共享文件夹后,重新编写读取程序,从而实现功能。在网上查找相关资料,但是都不是很全面,现在把相关代码分享,希望能帮到大家!依赖如下:&lt;dependencies&gt; &lt;dependency&gt; 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”。