You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

添加\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 neuline variable gets set to "" + "\n" then immediately overwritten with smsg + "\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 \n as 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's run method. 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 \r instead of \r\n.
  • If activeBT.write uses a buffered stream, make sure to call flush() after writing to force the data to be sent right away instead of waiting for the buffer to fill.

内容的提问来源于stack exchange,提问作者You Nes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:41:17