问题
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