"Halo, Amigo! Wingi Rishi ngandhani sampeyan babagan FileInputStream lan FileOutputStream . Lan dina iki aku bakal ngandhani babagan kelas FileReader lan FileWriter ."
Kaya sing wis sampeyan duga, kabeh kelas kasebut minangka adaptor antarane obyek File lan InputStream , OutputStream , Reader , lan Writer «antarmuka».
"Padha padha karo adaptor antarane File lan Reader / Writer, nanging sampeyan mung kudu pass obyek String kanggo konstruktor, ora File!"
"Bener, padha duwe sawetara konstruktor. Ana konstruktor kanggo obyek File lan String. Yen sampeyan pass obyek String kanggo konstruktor, banjur konstruktor quietly nggawe obyek Gambar nggunakake path file dijupuk saka obyek String liwati."
Iki kanggo penak. Pencipta Jawa njupuk kasus panggunaan sing paling kerep kanggo kelas kasebut lan nulis konstruktor kanggo kabeh. Iku cukup trep, apa ora?
"Oh, ya. Trep. Aku setuju. Nanging kenapa aku kudu terus-terusan nulis: "
BufferedReader bufferedReader = BufferedReader anyar (InputStreamReader anyar (System.in));
"Yagene dheweke ora nambah kasus panggunaan iki?"
"Masalah ing kene yaiku program Java sing khas ora bisa digunakake karo konsol. Bener, sampeyan meh ora nate maca apa-apa. Malah karo server web, server aplikasi, utawa sawetara sistem rumit liyane."
Nanging kita duwe PrintStream kanggo output data lan teks menyang console. Amarga «aplikasi server» iki asring nggunakake console kanggo nampilake status, kesalahan, lan kabeh jinis informasi liyane.
"Get. Lan sampeyan uga bisa nyalin file nggunakake FileReader lan FileWriter?"
"Ya, yen file teks (yaiku kalebu karakter). Iki contone:"
public static void main(String[] args) throws Exception
{
FileReader reader = new FileReader("c:/data.txt");
FileWriter writer = new FileWriter("c:/result.txt");
while (reader.ready()) //as long as there are unread bytes in the input stream
{
int data = reader.read(); //Read one character (the char will be widened to an int)
writer.write(data); //Write one character (the int will be truncated/narrowed to a char)
}
//Close the streams after we done using them
reader.close();
writer.close();
}
"Meh ora ana bedane."
"Ya, bedane minimal."
GO TO FULL VERSION