簡體   English   中英

使用java在JavaScript中創建文件

[英]use java to create file in JavaScript

首先,我是iMacros腳本編寫者。 這是用於編寫文件的java函數(不完全完整,但你會得到這個想法)

 bufferedWriter = new BufferedWriter(new FileWriter(filename));

            //Start writing to the output stream
            bufferedWriter.write("Writing line one to file");

現在,下面是JavaScript中用來執行與上述函數相同的任務的java函數,我在iMacros中運行該.js文件。 奇跡般有效。

//Function to write the file
function writeFile(filename, data)
{
   try
   { 

      //write the data

      out = new java.io.BufferedWriter(new java.io.FileWriter(filename, true));
      out.newLine();
      out.write(data);
      out.close();
      out=null;
   }
   catch(e)   //catch and report any errors
   {
      alert(""+e);
   }
}

現在我需要一個java函數,它將在硬盤驅動器位置創建文件和文件夾,我發現了這一點。

package com.mkyong.file;

import java.io.File; import java.io.IOException;

public class CreateFileExample 
{
    public static void main( String[] args )
    {   
        try {

          File file = new File("c:\\newfile.txt");

          if (file.createNewFile()){
            System.out.println("File is created!");
          }else{
            System.out.println("File already exists.");
          }

        } catch (IOException e) {
          e.printStackTrace();
    }
    }
}

但現在我需要java函數來創建文件夾和一個空文件(具有不同的擴展名,如.txt .csv等),該函數將在JavaScript中運行。

任何人都可以從上面兩個例子中給我一些指導方針嗎? 如何用Java編寫函數並在JavaScript中運行?

我不會聲稱完全理解這個問題,但這是如何確保某個目錄存在,並在其中創建一個隨機文件:

// make the dir and ensure the entire path exists
File destinationDir = new File("c:\\whereever\you\want\that\file\to\land").mkdirs();
// make some file in that directory
File file = new File(destinationDir,"whateverfilename.whateverextension");
// continue with your code
if (file.createNewFile()){
    System.out.println("File is created!");
}else{
    System.out.println("File already exists.");
}

此函數用於iMacros .js文件。 它是一個用JavaScript調用的Java方法。

createFile("C:\\testingfolder","test.csv");

function createFile(folder,file)
{

destinationDir = new java.io.File(folder).mkdirs();
file = new java.io.File(folder,file);
file.createNewFile();
}

該函數創建文件夾,並在其中創建文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM