java - 在 Linux 上使用 Java CIFS 客户端库发送文件
问题描述
我尝试将带有打印数据(来自 Zebra 打印机的数据)的文件从 Linux 机器发送到 Windows 机器上的共享打印机,但它不起作用,我尝试了一切。我的最后一个想法是先尝试在 Linux 机器上通过命令行工作,然后在 Java 中做同样的解决方案,结果是:它通过命令行工作,但在 Java 中不行。
我在 Linux 上的命令行解决方案有:
smbclient \\\\host\\printer_share -U 'domain/user%pass' -c "put file_name"
使用smbclient的解决方案效果很好,所以我考虑在 Java 中使用jCIFS,但它在打印机中不起作用。在同一主机的共享文件夹中它可以工作,但在打印机共享中没有,但是通过带有 smbclient 的命令行可以工作。有人知道我哪里出错了吗?
我的java代码:
public static void sendFileToPrinter(String commandsToPrinter) {
String user = "user";
String pass = "pass";
String domain = "domain";
String path = "smb://host/printer_share/file_to_print";
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(domain, user, pass);
SmbFile smbFile = new SmbFile(path, auth);
SmbFileOutputStream smbfos = new SmbFileOutputStream(smbFile);
smbfos.write(commandsToPrinter.getBytes());
System.out.println("Work");
}
Java错误:
解决方案
对操作系统漠不关心,我能够在@HieryNomus 的帮助下解决问题,他有一个完美的库来实现 SMB。Git 链接:https ://github.com/hierynomus/smbj/
对于我的需要,我通过以下实现实现(这只是我的测试代码):
public static void sendCommandToZebraPrinter(String command) throws MalformedURLException, SmbException, IOException {
String username = "username";
String password = "password";
String domain = "mydomain";
String sharedDirectory = "PRINTER_SHARE";
String computerName = "MYCOMPUTER";
SMBClient client = new SMBClient();
try (Connection connection = client.connect(computerName)) {
AuthenticationContext ac = new AuthenticationContext(username, password.toCharArray(), domain);
Session session = connection.authenticate(ac);
try (PrinterShare share = (PrinterShare) session.connectShare(sharedDirectory)) {
InputStream stream = new ByteArrayInputStream(command.concat("\n").getBytes(StandardCharsets.UTF_8));
share.print(stream);
}
}
}
命令变量为 Zebra 打印机(GC420t)的 EPL 命令,如:
I8,A,001
Q104,024
q863
rN
S2
D11
ZT
JF
OD
R172,0
f100
N
75,33,D,h3,"1"
b363,39,D,h2,"TEST"
b198,33,D,h3,"TEST"
LO154,4,1,73
LO280,4,1,73
A149,27,2,2,1,1,N,"1"
A272,26,2,3,1,1,N,"TEST"
A425,26,2,3,1,1,N,"TEST"
P1
如果命令不起作用:\n
在命令末尾添加。
推荐阅读
- javascript - 获取 Javascript 对象中的属性
- javascript - 我怎样才能找到这个父类别的.children
- css - 使用 @supports selector() 尽管 Sass 不支持它
- apache-spark - 来自 pyspark 的 Hive 查询
- kubernetes - k8s - 即使边车坠毁也能保持 pod
- c++ - C ++一个线程如何正确通信其任务已完成?
- bash - 如何使用 AWK 将文件中的非 ASCII 字符读取为 ASCII
- c - 在 C 中设置函数调用所消耗的分析时间
- git - 如何提交对我不拥有且未分叉的存储库的更改的拉取请求?
- c# - 如何在 C# 中将数据发送到 ASP.NET Core MVC 控制器?