Reading local server .json file with mobileFirst javascript adapter

不羁岁月 提交于 2019-12-11 05:35:28

问题


Is there any way that I can read a .json file (located in server) from a javascript http adapter? I tried a lot of methods described in the internet but they don't seem to work because they are made for browser javascript (I get errors like XMLHttpRequest is not defined or activeObject is not defined).

for example, I used this but it doesn't work:

function readTextFile(file)
{
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function ()
    {
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                return allText;
            }
        }
    }
    rawFile.send(null);
}  

Is there any way that I could do this without using java?


回答1:


You can read a file with Javascript as shown below.

function readFile(filename) {
    var content = "";

    var fileReader = new java.io.FileReader(filename);

    var bufferedReader = new java.io.BufferedReader(fileReader);

    var line;

    while((line = bufferedReader.readLine()) != null) {
        content += line;
    }   

    bufferedReader.close();

    return content;
}

function test() {
    var file = 'yourfilename.json';
    var fileContents;
    try {
         fileContents = JSON.parse(readFile(file));     
    }  catch(ex) {
        // handle error                
    }

    return  {
        fileContents: fileContents
    };
}



回答2:


For those interested in using Java.

One thing you can do is create a Javascript adapter which will use Java code. It is pretty simple to set up.

First create a Javascript adapter.

Then create a Java class under the server/lib folder. I created the class ReadJSON.java under the package com.sample.customcode.

Inside the ReadJSON.java

public class ReadJSON {
    public static String readJSON() throws IOException {
       //Open File
        File file = new File("file.txt");
        BufferedReader reader = null;
        try {
           //Create the file reader
            reader = new BufferedReader(new FileReader(file));
            String text = null;

            //read file
            while ((text = reader.readLine()) != null) {}
        } finally {
             try {
                 //Close the stream
                 reader.close();
             } 
        }
        return "the text from file";
    }
}

Inside your javascript adapter you can use Java methods like below:

function readJOSN() {
    var JSONfromServer = com.sample.customcode.ReadJSON.readJSON();
    return {
        result: JSONfromServer
    };

}

Hope this helps.



来源:https://stackoverflow.com/questions/37414618/reading-local-server-json-file-with-mobilefirst-javascript-adapter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!