-1

I am creating an Android module in react-native

I never worked with Java or writing code in Java

How can I complete the code below?

What I want

1- look and verify if the directory exist if it exist then remove it.

2- recreate the directory.

3- create a json file and add its content.

Here is what I got so far

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

Update and solution

After to much hard work this did thing for me.

Here is the complete code for anyone who have similar problem.

// 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);
    }
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Alen.Toma
  • 4,684
  • 2
  • 14
  • 31
  • 1
    1. `javax.naming.spi.DirectoryManager` is **almost certainly** not what you want to use, it has nothing to do with the kinds of directories you are thinking of. 2. Java is case sensitive and the class is named `String` and not `string`. 3. The `var` keyword was introduced in Java 10, so if you're compiling with or for an older version, it's not available (and the error messages suggest that you are). 4. You're missing imports for `Environment`, `OutputStreamWriter` and `FileOutputStream`. All in all: if you've not done any Java before, then please do at least a basic Java tutorial first. – Joachim Sauer Jul 10 '21 at 09:05
  • `content == ""` please read [How do I compare strings in Java?](https://stackoverflow.com/q/513832) or in this case use `content.isEmpty()`. – Pshemo Jul 10 '21 at 14:26
  • Believe me when I tell you that this is my first time writing in java. So I believe I did pretty good. – Alen.Toma Jul 10 '21 at 15:36
  • Your first time writing Java should not combine **multiple** technologies that you are entirely unfamiliar with. That's why you should be doing a basic Java tutorial before touching this kind of thing. Even if you're experienced in other languages already (that should only speed up the process). Trying to jump into the deep end of the pool without having waded into the shallow end is not way to get results faster, it's a way to drown in problems that you don't know how to fix. – Joachim Sauer Jul 13 '21 at 12:35

2 Answers2

1

To delete directory

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

To write to file

public void writeToFile(String content, File file) throws IOException {
    Files.write(file.toPath(), content.getBytes());
}
anish sharma
  • 568
  • 3
  • 5
0

You can use Apache FileUtils to perform all the required operations for e.g.

Reference : 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
dassum
  • 4,727
  • 2
  • 25
  • 38