2012-12-07 100 views
1

首先我是iMacros腳本編寫器。 這是Java函數寫一個文件(沒有完全完成,但你的想法)使用java在JavaScript中創建文件

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

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

現在波紋管在JavaScript用來做同樣的任務,因爲上述功能的Java功能,我運行的.js iMacros中的文件。奇蹟般有效。

//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(); 
    } 
    } 
} 

但現在我需要將創建文件夾和一個空文件(比如後綴名爲.txt的.csv等不同的擴展名)的Java的功能和作用將在JavaScript工作。

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

+0

文件有一個方法[mkdirs()](http://docs.oracle.com/javase/6/docs/api/java/io/File.html#mkdirs%28%29),它會創建缺少的子目錄但我懷疑這不會對你有很大的幫助。儘管名稱相似,但Java和Javascript是兩種完全不同的語言,大多生活在不同的環境中。你需要澄清你需要什麼,我特別困惑'現在bellow是在JavaScript中用來執行與上述功能相同的任務的java函數,我在iMacros中運行該.js文件。像一個魅力工作。「這似乎建議你以某種方式已經從JavaScript調用Java? – fvu

+0

「這似乎建議你以某種方式已經從JavaScript調用Java?」是的! 由於JavaScript無法寫入文件,我使用Java並在JavaScript中調用它來寫入文件。因此,上面有JavaScript調用的Java方法來打開和寫入文件中的文本。所以我舉了一個例子,說明我如何在JavaScript文件中使用Java,並按下Play來在iMacros中執行這項工作。所以從這個例子我需要在那個文件夾中創建文件夾和文件的功能。你現在明白了? – macroscripts

回答

2

此功能在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(); 
} 

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

2

我不會要求要充分認識這個問題,但這是如何確保一些目錄存在,並在其中創建一個隨機文件:

// 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."); 
} 
+0

我用你的例子,寫了這個 destinationDir = new java.io.File(「c:\\ testingfolder」)。mkdirs(); 它的工作!我創建了一個新文件夾,但是當我寫這個文件時 file = new java.io.File(destinationDir,「test.csv」);它並沒有在該文件夾中創建新文件... 而當我寫這個file.createNewFile();我有一個錯誤。 java.io.IOException:系統找不到指定的路徑(錯誤代碼:991) 幾乎在那裏! – macroscripts

+0

我找到了一個解決方案。你幫了我很多的人。真的。我會在這裏寫一個解決方案,如果有人需要它,他們可以使用它。 – macroscripts