我对Java和Android知之甚少。我试图做的是在一个Android应用程序中打开/dev/ttyS0,它应该与串行线通信,但我迷路了。
我的设备是根设备,从命令行我可以"echo ...>/dev/ttyS0“,也可以从它读取,但我在Java中尝试这样做时迷失了方向。开始时,我找不到一种方法可以在简单的读写模式下打开文件,而不需要处理缓冲区和其他复杂问题(显然,我想要无缓冲的I/O)。
我在互联网上搜索,但所有的例子都指的是USB,这对我来说是不可用的。然后我找到了UartDevice类,但它是一个类,可以从中派生出适当的实现。
我尝试使用File类,并将Reader和Writer类都附加到它,但编译器抱怨说,坦率地说,我不确定这是不是可行的方法。我需要一个框架代码来开始;我错过了一个简单的TextFile类,它具有在同一个打开的文件上同时使用的无缓冲的read()和write()方法!
有人能告诉我怎么走吗?谢谢。
发布于 2019-07-08 20:45:07
经过多次尝试,在SO网站提供的大量信息的帮助下,我终于成功完成了任务。代码如下:
public class MainActivity
extends AppCompatActivity {
File serport;
private FileInputStream mSerR;
private FileOutputStream mSerW;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// let this program to access the serial port, and
// turn off the local echo. sudo() is a routine found here on S.O.
sudo("chmod a+rw /dev/ttyS0");
sudo("stty -echo </dev/ttyS0");
// open the file for read and write
serport = new File("/dev/ttyS0");
try {
mSerR = new FileInputStream(serport);
mSerW = new FileOutputStream(serport);
} catch (FileNotFoundException e) {}
// edLine is a textbox where to write a string and send to the port
final EditText edLine = (EditText) findViewById(R.id.edLine);
// edTerm is a multiline text box to show the dialog
final TextView edTerm = findViewById(R.id.edTerm);
// pressing Enter, the content of edLine is echoed and sent to the port
edLine.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button
if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
// Perform action on key press
String cmd = edLine.getText()+"\n";
edTerm.append(cmd);
byte[] obuf = cmd.getBytes();
try {
mSerW.write(obuf);
} catch (IOException e) {}
edLine.setText("");
// read the reply; some time must be granted to the server
// for replying
cmd = "";
int b=-1, tries=8;
while (tries>0) {
try {
b = mSerR.read();
} catch (IOException e) {}
if (b==-1) {
try {
Thread.sleep(5);
} catch (InterruptedException e) {}
--tries;
} else {
tries=3; // allow more timeout (more brief)
if (b==10) break;
cmd = cmd + (char) b;
}
}
// append the received reply to the multiline control
edTerm.append(cmd+"\n");
return true;
}
return false;
}
});
}
}
发布于 2019-07-06 15:59:33
Java中的所有文件访问都是通过输入流和输出流完成的。如果你想打开一个文件,你只需为它创建一个FileOutputStream或FileInputStream。这些是无缓冲的流。如果您想要写入原始字节,可以将其包装在ByteArrayOutputStream或ByteArrayInputStream中。
这将为您完成字符转换。只是不要使用FileWriter-虽然它看起来很合适,但它没有选择字符集的选项,默认也不是ascii。要读入,请使用InputStreamReader。
https://stackoverflow.com/questions/56911912
复制相似问题