Исключение нулевого указателя - это индикатор того, что вы используете объект, не инициализируя его.
Например, ниже - класс ученика, который будет использовать его в нашем коде.
public class Student {
private int id;
public int getId() {
return this.id;
}
public setId(int newId) {
this.id = newId;
}
}
Приведенный ниже код дает вам исключение с нулевым указателем.
public class School {
Student obj_Student;
public School() {
try {
obj_Student.getId();
}
catch(Exception e) {
System.out.println("Null Pointer ");
}
}
}
Поскольку вы используете Obj_Student
, но вы забыли инициализировать его, как в правильном коде, показанном ниже:
public class School {
Student obj_Student;
public School() {
try {
obj_Student = new Student();
obj_Student.setId(12);
obj_Student.getId();
}
catch(Exception e) {
System.out.println("Null Pointer ");
}
}
}
http://winscp.net является бесплатным, доступен для сценариев, поддерживает пассивный режим и определенно ОТЛИЧНО.
Вышеупомянутый скрипт велик. Я использовал следующие команды для загрузки файлов, а также для вывода вывода в файл, который полезен при отладке, и это распространенное заблуждение, что windows ftp не может выполнять пассивный режим, чтобы команда пассивная была " quote pasv "(я добавил это в скрипт
Sub FtpFileto()
Set FSO = CreateObject("scripting.filesystemobject")
F = "C:\FTPScript.txt"
' Create the ftpscript to be run
Open F For Output As #1
Print #1, "open ftp.server.com" 'replace ftp.server with the server address
Print #1, "ID" 'login id here
Print #1, "PWD" 'login password here
Print #1, "quote pasv" ' passive mode ftp if needed
Print #1, "cd " & " /dir" 'Directory of file location
Print #1, "cd " & " subdir" 'Sub-Directory of file location
Print #1, "ascii"
Print #1, "prompt"
'Put the file from the host and save it to the specified directory and filename
Print #1, "put " & VREDET; """C:\file1.csv"""; ""
Print #1, "put " & VREDET; """C:\file2.csv"""; ""
Print #1, "put " & VREDET; """C:\file3.csv"""; ""
Print #1, "disconnect" 'disconnect the session
Print #1, "bye"
Print #1, "exit"
Close #1
'Now for the command to upload to the ftpsite and log it to a text file
' the trick is to use the standard command shell which allows logging
Shell "cmd /c C:\WINDOWS\system32\ftp.exe -i -s:C:\FTPScript.txt > c:\ftpuploadlog.txt", vbHide
End Sub
ftp.exe
не поддерживает пассивный режим . Использование quote pasv
не может помочь.
– Martin Prikryl
14 August 2015 в 06:59
Диего, я использовал код ниже успешно в течение многих лет. Код получает файлы с хоста, но я уверен, что он может быть изменен для размещения там файлов.
'Start Code
Set FSO = CreateObject("scripting.filesystemobject")
'************************************************************************************** '*** Create FTP Action File & Initiate FTP File Transfer
'************************************************************************************** VREDET = filename1 'Variable holding name of file to get
F = "C:\Volume\Temp\FTPScript.txt" 'creates the file that holds the FTP commands
Open F For Output As #1
Print #1, "open ftp.server" 'replace ftp.server with the server address
Print #1, ID 'login id here
Print #1, PW 'login password here
Print #1, "cd " & " Folder1" 'Directory of file location
Print #1, "cd " & " Folder2" 'Sub-Directory of file location
Print #1, "ascii"
Print #1, "prompt"
'Get the file from the host and save it to the specified directory and filename
Print #1, "get " & VREDET; " C:\some\directory\" & another-filename & ".CSV"
Print #1, "disconnect" 'disconnect the session
Print #1, "bye"
Print #1, "exit"
Close #1
'identify folder where ftp resides and execute the FTPScript.txt file
'vbHide - hides the FTP session
If FSO.FolderExists("C:\Windows\System32") = False Then
Shell "C:\WINNT\system32\ftp.exe -s:C:\Volume\Temp\FTPScript.txt", vbHide
Else
Shell "C:\WINDOWS\system32\ftp.exe -s:C:\Volume\Temp\FTPScript.txt", vbHide
End If
'end code
Если вы не можете использовать Windows ftp.exe
(особенно потому, что не поддерживает пассивный режим и TLS / SSL), вы можете использовать другой FTP-клиент командной строки.
Например, чтобы загрузить файл с помощью скриптов WinSCP , используйте:
Call Shell( _
"C:\path\WinSCP.com /log=C:\path\excel.log /command " & _
"""open ftp://user:password@example.com/"" " & _
"""put C:\path\file.txt /path/"" " & _
"""exit""")
. Чтобы облегчить чтение, приведенные выше команды WinSCP:
open ftp://user:password@example.com/
put C:\path\file.txt /path/
exit
Вы можете поместить команды в файл сценария и запустить скрипт с параметром командной строки /script=
, аналогично ftp -s:
, вместо /command
.
См. руководство по Преобразование сценария Windows FTP в скрипт WinSCP .
Вы даже можете WinSCP GUI генерировать сценарий загрузки FTP для вас.
WinSCP по умолчанию переходит в пассивный режим.
Вы также можете использовать FTPS (TLS / SSL) :
open ftpes://user:password@example.com/
В качестве альтернативы вы можете использовать сборку WinSCP .NET через COM из кода VBA.
(я автор WinSCP)