การใช้ StringWriter สำหรับสร้างข้อความแบบ Dynamic ใน Android
ตัวอย่างสาธิตการใช้ java.io.StringWriter ร่วมกับ append() เพื่อสร้างสตริงอย่างมีประสิทธิภาพ แล้วแสดงใน TextView
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
Android Studio → File → New Project
ขั้นตอนที่ 2: Layout XML (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center_horizontal"
android:layout_marginTop="30dp"
tools:context=".MainActivity">
<EditText
android:id="@+id/edit_query"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="กรอกข้อความ..." />
<Button
android:id="@+id/buttonPanel"
android:text="Append with StringWriter"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:layout_marginTop="16dp" />
</LinearLayout>
ขั้นตอนที่ 3: โค้ด Java (src/MainActivity.java)
package com.example.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.io.StringWriter;
public class MainActivity extends AppCompatActivity {
TextView text;
EditText edit_query;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit_query = findViewById(R.id.edit_query);
text = findViewById(R.id.text);
findViewById(R.id.buttonPanel).setOnClickListener(new View.OnClickListener() {
@RequiresApi(api = Build.VERSION_CODES.KITKAT) // API 19+ for StringWriter.append(CharSequence)
@Override
public void onClick(View v) {
String input = edit_query.getText().toString();
if (!input.isEmpty()) {
// ใช้ StringWriter สร้างข้อความ
StringWriter sw = new StringWriter();
sw.append("String Writer: ");
sw.append(input);
sw.append(" [Appended at ").append(java.time.LocalTime.now().toString()).append("]");
// แสดงผล
text.setText(sw.toString());
// Clear input
edit_query.setText("");
}
}
});
}
}
การทดสอบ
รันแอป กรอกข้อความใน EditText กดปุ่ม จะแสดงใน TextView: String Writer: ข้อความของคุณ [Appended at 14:30:00]

StringWriter vs StringBuilder vs StringBuffer
| Class | Thread-safe | Implements | ใช้เมื่อไหร่ |
|---|---|---|---|
| StringBuilder | ไม่ | CharSequence, Appendable | ทั่วไป (Performance ดีที่สุด) |
| StringBuffer | ใช่ (Synchronized) | CharSequence, Appendable | Multi-thread environment |
| StringWriter | ไม่ | Writer, Appendable, Closeable, Flushable | ต้องการ Writer API (เช่น PrintWriter, JSON Writer) |
เมื่อไหร่ควรใช้ StringWriter?
- ต้องการส่งให้ API ที่รับ
Writer(เช่นPrintWriter,JsonWriter,XMLSerializer) - ต้องการ
flush(),close()semantics - รวมกับ I/O Pipeline
ตัวอย่างใช้กับ PrintWriter (จัดรูปแบบ)
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
pw.printf("User: %s, Score: %d, Rate: %.2f%n", name, score, rate);
pw.println("--- Report End ---");
text.setText(sw.toString());
ตัวอย่างใช้กับ JSON (JsonWriter)
StringWriter sw = new StringWriter();
JsonWriter writer = new JsonWriter(sw);
writer.beginObject()
.name("name").value(userName)
.name("score").value(score)
.name("timestamp").value(System.currentTimeMillis())
.endObject();
writer.close();
String json = sw.toString(); // {"name":"John","score":100,"timestamp":1234567890}
Performance Note
สำหรับการต่อ String ธรรมดา ให้ใช้ StringBuilder (เร็วกว่า, เบากว่า)
// แทน StringWriter
StringBuilder sb = new StringBuilder();
sb.append("String Writer: ");
sb.append(input);
text.setText(sb.toString());
สรุป
StringWriter เหมาะสำหรับการทำงานกับ Writer-based APIs (JSON, XML, PrintWriter) สำหรับ String Concatenation ธรรมดา ให้ใช้ StringBuilder