添加\n后仍无法在文件中换行写入字符串,附代码求解决方案
解决蓝牙写入时换行失效的问题
Hey there! Let's figure out why your newline isn't working and fix this up properly.
问题分析
Looking at your code, there are a few issues causing the problem (plus some unnecessary extra code):
- 冗余的变量赋值: Your
neulinevariable gets set to"" + "\n"then immediately overwritten withsmsg + "\n"—that first line does nothing at all, though it's not the main culprit here. - 错误的换行符: Most Bluetooth/serial devices don't recognize a single
\nas a valid newline. They expect the carriage return + line feed pair (\r\n) to trigger a line break. - 阻塞的定时器线程: You wrapped the send logic in an infinite
for (;true;)loop inside the TimerTask'srunmethod. This will completely lock up the timer thread, meaning the timer can't run its scheduled tasks as intended (it's stuck in that loop forever).
修正后的代码
Here's a cleaned-up, fixed version of your code:
Timer t = new Timer(); t.scheduleAtFixedRate(new TimerTask() { @Override public void run() { // Use \r\n for proper newline support in most BT/serial devices String smsg = "$;TRIG;\r\n"; activeBT.write(smsg.getBytes()); // If activeBT uses an OutputStream, you might need to flush to ensure data is sent immediately: // activeBT.flush(); } }, 0, 100);
额外排查点(如果问题仍存在)
- Double-check the receiving device's newline configuration—some rare systems only use
\rinstead of\r\n. - If
activeBT.writeuses a buffered stream, make sure to callflush()after writing to force the data to be sent right away instead of waiting for the buffer to fill.
内容的提问来源于stack exchange,提问作者You Nes
相关产品推荐
相关产品推荐

