Android: чтение имени папки удаленного расположения и имени файла - PullRequest
0 голосов
/ 23 ноября 2018

Я подключен к серверу с адресом 192.168.1.254, и после ввода этого адреса в браузере отображается список доступных папок enter image description here Я хочу отобразить имя папки вмое приложение для Android я попробовал следующий код, но не повезло.

try {
        SmbFile test = new SmbFile("smb://192.168.1.254");
        SmbFile[] files = test.listFiles();
        if (files != null)
            for (SmbFile s : files) {
                Log.d("debug", s.getName());
            }
    } catch (SmbException e) {
        Log.d("debug", "ERROR");
    } catch (Exception e) {
        Log.d("debug", "ERROR");
    }

который я нахожу здесь и я также попытался

File f = new File("//192.168.1.254");
//also tried with File f = new File("http//192.168.1.254");
File[] files = f.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
    // Specify the extentions of files to be included.
    return name.endsWith(".bmp") || name.endsWith(".gif");
}
});

 // get names of the files
String[] fileNamesArray = null; 
for (int indx = 0; indx < files.length(); indx++) {
Log.d("name",files[indx].getName());
}

return fileNamesArray; 

Ответы [ 2 ]

0 голосов
/ 02 декабря 2018

Один из способов - загрузить html в виде строки с сервера.Затем используйте

 urlConnection = new URL("your_url").openConnection();
 reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

 while ((String line = reader.readLine()) != null) {
            stringBuilder.append(line).append("\n");
        }
 String your_data = Html.fromHtml(stringBuilder.toString());

Это будет содержать таблицу в текстовом формате.Вы можете обработать его, чтобы получить необходимые данные.

0 голосов
/ 27 ноября 2018

Кажется, вам нужен FTP-клиент для списка файлов в удаленном местоположении.Попробуйте использовать, например, ftp4j библиотеку, как описано в официальной документации или в этом примере Android , devert.Точный список файлов на удаленном FTP-сервере с ftp4j Арун вы можете найти здесь :

    FTPClient client = null;
    try {       // Get the FTP Connection from the
        Utility class client =FTPUtility.connect(ipAddress, userName,
                password);
        if (client != null) {           /* List all file inside the directory */
            FTPFile[] fileArray = client.list();
            System.out.println("List of files...");
            for (int i = 0; i < fileArray.length; i++) {
                FTPFile file = fileArray[i];
                if (file != null) {
                    if (file.TYPE_FILE == FTPFile.TYPE_FILE) // File                    {
                        System.out.println("File Name = " + file.getName() + " ; File Size = " + file.getSize() + " ;Modified Date = " + file.getModifiedDate());
                } else if (file.TYPE_DIRECTORY == FTPFile.TYPE_DIRECTORY) // Directory
                {
                    System.out.println("Directory Name = " + file.getName() + " ; Directory Size = " + file.getSize() + " ;Modified Date = " + file.getModifiedDate());
                } else if (file.TYPE_LINK == FTPFile.TYPE_LINK) // Link
                {
                    System.out.println("Link Name = " + file.getName() + " ;Modified Date = "
                            + file.getModifiedDate());
                }
            }
        }
    }
}   catch(
Exception e)

{
    System.err.println("ERROR : Error in Connecting to Remote Machine... Hence exitting...");       //
    e.printStackTrace();
    System.exit(2);
}

finally

{
    try {
        client.disconnect(true);
    } catch
            (Exception e) {
    }
}

Обновление

Если «нет активного порта для ftp, и в настоящее время я обнаружил, что устройство имеет только 4 активных порта, т.е. 80,443,3333,8192», кажется, список файлов отправляется по HTTP, и вы можете загрузить его через HttpURLConnection и анализ ответа.Примерно так:

HttpURLConnection connection = null;
BufferedReader reader = null;

try {
    URL url = new URL("http://192.168.1.254");

    connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.connect();

    int responseCode = connection.getResponseCode();

    InputStream stream = connection.getInputStream();

    reader = new BufferedReader(new InputStreamReader(stream));
    StringBuilder responseStringBuilder = new StringBuilder();

    String line = "";

    while ((line = reader.readLine()) != null) {
        responseStringBuilder .append(line);
        responseStringBuilder .append("\n");
    }

    // Parse responseStringBuilder.toString() (probably as HTML) here:
    ... 

} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (connection != null) {
        connection.disconnect();
    }
    try {
        if (reader != null) {
            reader.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
...