【问题标题】:How to create a json file and its content如何创建 json 文件及其内容
【发布时间】:2021-07-10 07:33:49
【问题描述】:

我正在react-native中创建一个Android模块

我从未使用过 Java 或用 Java 编写代码

如何完成下面的代码?

我想要什么

1-查看并验证目录是否存在,如果存在则将其删除。

2- 重新创建目录。

3- 创建一个 json 文件并添加其内容。

这是我目前得到的结果

@ReactMethod
public string write(string content) {
    var folder = "NovelManager";
    File path = Paths.get(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), folder);
    var fullPath = Paths.get(path, "NovelManager.backup.json");

    makeDir(path);
    File file = new File(path, "NovelManager.backup.json");
    if (!file.exists())
        file = file.createNewFile();

    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8));

    out.write(content);
    out.close();

    return file.getAbsolutePath();
}

private void makeDir(string dirPath){
    var dir = new File(dirPath);
    if (!dir.exists())
    dir.mkdir();
}

更新及解决方案

经过艰苦的努力,这对我来说确实有用。

这里是任何有类似问题的人的完整代码。

// DownloadFileModule.java
package com.novelmanager;

import android.view.View;
import android.app.Activity;

import java.io.BufferedWriter;
import java.io.Console;
import java.io.File;
import java.io.FileWriter;
import android.os.Environment;
import java.io.OutputStreamWriter;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;

import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.UiThreadUtil;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;

public class DownloadFileModule extends ReactContextBaseJavaModule {
    @Override
    public String getName() {
        return "DownloadFileModule";
    }

    @ReactMethod(isBlockingSynchronousMethod = true)
    public String write(String content) {
        if (content == null || content == "")
            return "";
        try {

            String folder = "NovelManager";
            String fileName = "NovelManager.backup.json";
            String downloadFolderPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                    .getPath();
            String dirPath = compine(downloadFolderPath, folder);
            File dir = new File(dirPath);
            if (!dir.exists())
                dir.mkdir();

            String path = compine(downloadFolderPath, folder, fileName);

            File file = new File(path);
            if (!file.exists())
                file.createNewFile();

            BufferedWriter out = new BufferedWriter(
                    new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8));

            out.write(content);
            out.close();
            return file.getPath();
        } catch (Exception e) {
            return e.getMessage();
        }

    }

    private String compine(String... more) {
        String url = more[0];

        for (int i = 1; i < more.length; i++) {
            String str = more[i];
            if (str.startsWith("/"))
                str = str.substring(1);
            if (str.endsWith("/"))
                str = str.substring(0, str.length() - 1);

            if (url.endsWith("/"))
                url = url.substring(0, url.length() - 1);

            url = url + "/" + str; // relative url
        }

        return url; // relative url
    }

    DownloadFileModule(ReactApplicationContext reactContext) {
        super(reactContext);
    }
}

【问题讨论】:

  • 1. javax.naming.spi.DirectoryManager几乎可以肯定不是您想要使用的,它与您所考虑的目录类型无关。 2. Java 区分大小写,类名为String 而不是string。 3. var 关键字是在 Java 10 中引入的,因此如果您正在使用或为旧版本进行编译,则它不可用(并且错误消息表明您是可用的)。 4. 您缺少 EnvironmentOutputStreamWriterFileOutputStream 的导入。总而言之:如果您之前没有学过任何 Java,那么请至少先做一个基本的 Java 教程。
  • content == "" 请阅读How do I compare strings in Java? 或在这种情况下使用content.isEmpty()
  • 相信我,这是我第一次用 java 编写代码。所以我相信我做得很好。
  • 您第一次编写 Java 时不应结合您完全不熟悉的多种技术。这就是为什么在接触这类东西之前你应该先做一个基本的 Java 教程。即使您已经有其他语言的经验(这只会加快进程)。试图在没有涉足浅水的情况下跳入池子的深处并不是更快获得结果的方法,而是一种淹没在您不知道如何解决的问题中的方法。

标签: java android react-native


【解决方案1】:

删除目录

public boolean deleteDirectory(Path pathToBeDeleted) throws IOException {
    Files.walk(pathToBeDeleted)
      .sorted(Comparator.reverseOrder())
      .map(Path::toFile)
      .forEach(File::delete);
    
    return !Files.exists(pathToBeDeleted);
}

写入文件

public void writeToFile(String content, File file) throws IOException {
    Files.write(file.toPath(), content.getBytes());
}

【讨论】:

  • 抱歉,这不是我想要的完整示例。
【解决方案2】:

您可以使用 Apache FileUtils 执行所有必需的操作,例如

参考:https://commons.apache.org/proper/commons-io/javadocs/api-2.5/index.html?org/apache/commons/io/FileUtils.html

    FileUtils.cleanDirectory(path); //clean out directory (this is optional)
    FileUtils.forceDelete(path); //delete directory
    FileUtils.forceMkdir(path); //create directory
    FileUtils.touch(file)); //create new file

【讨论】:

  • 不能使用外部包。
猜你喜欢
  • 2020-09-21
  • 2013-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-09
  • 2015-03-30
  • 1970-01-01
  • 2012-12-16
相关资源
最近更新 更多