Di Java anda boleh membaca kandungan fail dalam pelbagai cara, salah satu caranya ialah membacanya sebagai aksara menggunakan String kelas java.util.Scanner, untuk tujuan ini, nyatakan kelas
ScannerBuat penimbal rentetan kosong.
Jika pengimbas mempunyai baris seterusnya, mulakan gelung while berdasarkan syarat. Iaitu
hasNextLine()Gunakan kaedah
append()Gunakan kaedah
toString()Contoh
li>Buat fail bernamaTutorials Point is an E-learning company that set out on its journey to provide knowledge to that class of readers that responds better to online content. With Tutorials Point, you can learn at your own pace, in your own space. After a successful journey of providing the best learning content at tutorialspoint.com, we created our subscription based premium product called Tutorix to provide Simply Easy Learning in the best personalized way for K-12 students, and aspirants of competitive exams like IIT/JEE and NEET.
Atur cara Java berikut membaca kandungan fail sample.txt < /p>
ke dalam rentetan dan mencetaknya. Atas ialah kandungan terperinci Bagaimanakah kita boleh membuat rentetan daripada kandungan fail dalam Java?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class FileToString {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(new File("E://test//sample.txt"));
String input;
StringBuffer sb = new StringBuffer();
while (sc.hasNextLine()) {
input = sc.nextLine();
sb.append(" "+input);
}
System.out.println("Contents of the file are: "+sb.toString());
}
}
Contents of the file are: Tutorials Point is an E-learning company that set out on its journey to
provide knowledge to that class of readers that responds better to online content. With Tutorials Point,
you can learn at your own pace, in your own space. After a successful journey of providing the best
learning content at tutorialspoint.com, we created our subscription based premium product called
Tutorix to provide Simply Easy Learning in the best personalized way for K-12 students, and aspirants
of competitive exams like IIT/JEE and NEET.