gpt4 book ai didi

java - 使用 java 在 JavaScript 中创建文件

转载 作者:行者123 更新时间:2023-11-29 03:39:42 25 4
gpt4 key购买 nike

首先,我是 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 函数来在硬盘驱动器位置创建文件和文件夹,我找到了这个。

打包com.mkyong.file;

导入java.io.文件;导入 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.");
}

关于java - 使用 java 在 JavaScript 中创建文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13754861/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com