Converting ByteBuffer To String remove linebreaks of string which are located at the end of String?

。_饼干妹妹 提交于 2020-08-09 08:08:07

问题


I write the following code in the android studio

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String hello = "Hello\n\n";
        ByteBuffer buffer2 = ByteBuffer.allocate(hello.getBytes().length);
        buffer2.put(hello.getBytes());
        buffer2.flip();
        while (true) {
            Log.d(TAG, new String(buffer2.array()));
        }
    }
}

It should print Hello with line breaks but as shown in the following screenshot it doesn't.


回答1:


Converting ByteBuffer To String remove linebreaks of string which are located at the end of String?

Answer: No


Demo:

import java.nio.ByteBuffer;

public class Main {
    public static void main(String[] args) {
        String hello = "Hello\n\n";
        ByteBuffer buffer2 = ByteBuffer.allocate(hello.getBytes().length);
        buffer2.put(hello.getBytes());
        buffer2.flip();

        System.out.println(new String(buffer2.array()) + "Hi");
    }
}

Output:

Hello

Hi


来源:https://stackoverflow.com/questions/63074942/converting-bytebuffer-to-string-remove-linebreaks-of-string-which-are-located-at

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!