"ํ์ผ ์ ๋ ฅ/์ถ๋ ฅ์ ์ํ ์คํธ๋ฆผ๋ถํฐ ์์ํ๊ฒ ์ต๋๋ค. ํ์ง๋ง ๊ฐ์ฅ ๋จผ์ ํด์ผ ํ ์ผ์ด ์์ต๋๋ค."
ํ์ผ ์ฝ๊ธฐ ๋ฐ ์ฐ๊ธฐ๋ฅผ ์ํ ๋ ๊ฐ์ง ํด๋์ค๊ฐ ์์ต๋๋ค: FileInputStream ๋ฐ FileOutputStream . ์ด๋ฏธ ์ง์ํ์ จ๊ฒ ์ง๋ง FileInputStream์ ํ์ผ์์ ๋ฐ์ดํธ๋ฅผ ์์ฐจ์ ์ผ๋ก ์ฝ์ ์ ์๊ณ FileOutputStream์ ํ์ผ์ ๋ฐ์ดํธ๋ฅผ ์์ฐจ์ ์ผ๋ก ์ธ ์ ์์ต๋๋ค. ๋ค์์ ์ด๋ฌํ ํด๋์ค์ ๋ฉ์๋์ ๋๋ค.
๋ฐฉ๋ฒ | ๋ฉ์๋๊ฐ ์ํํ๋ ์์ |
---|---|
|
โ ์์ฑ์์ ๋๋ค. ์์ฑ๋ ๊ฐ์ฒด๊ฐ ๋ฐ์ดํฐ๋ฅผ ์ฝ์ ๋์คํฌ์ ํ์ผ ์ด๋ฆ์ ์ง์ ํ ์ ์์ต๋๋ค. |
|
โ ์ด ๋ฉ์๋๋ ํ์ผ์์ ํ ๋ฐ์ดํธ๋ฅผ ์ฝ๊ณ ๋ฐํํฉ๋๋ค. ๋ฐํ ๊ฐ์ int๋ก ํ์ฅ๋ฉ๋๋ค. |
|
โ ์ด ๋ฉ์๋๋ ์ฝ์ง ์์(์ฌ์ฉ ๊ฐ๋ฅํ) ๋ฐ์ดํธ ์๋ฅผ ๋ฐํํฉ๋๋ค. |
|
โ ์ด ๋ฉ์๋๋ ์คํธ๋ฆผ์ ยซ๋ซ์ต๋๋คยป. ์คํธ๋ฆผ ์์
์ ๋ง์น๋ฉด ์ด๊ฒ์ ํธ์ถํฉ๋๋ค. ๊ทธ๋ฐ ๋ค์ ๊ฐ์ฒด๋ ํ์ผ ๋ฑ์ ๋ซ๋ ๋ฐ ํ์ํ ๊ด๋ฆฌ ์์ ์ ์ํํฉ๋๋ค. ์ด ์์ ์์ ์คํธ๋ฆผ์์ ๋ ์ด์ ๋ฐ์ดํฐ๋ฅผ ์ฝ์ ์ ์์ต๋๋ค. |
์ฌ๋ฏธ์ผ์ ํ์ผ์ ์๋ ๋ชจ๋ ๋ฐ์ดํธ์ ํฉ๊ณ๋ฅผ ๊ณ์ฐํด ๋ณด๊ฒ ์ต๋๋ค. ์ฝ๋๋ ๋ค์๊ณผ ๊ฐ์ต๋๋ค.
public static void main(String[] args) throws Exception
{
//Create a FileInputStream object bound to ยซc:/data.txtยป.
FileInputStream inputStream = new FileInputStream("c:/data.txt");
long sum = 0;
while (inputStream.available() > 0) //as long as there are unread bytes
{
int data = inputStream.read(); //Read the next byte
sum += data; //Add it to the running total
}
inputStream.close(); // Close the stream
System.out.println(sum); // Display the sum on the screen.
}
"์ฐ๋ฆฌ๋ ์ด๋ฏธ ์ด์ ๊ฐ์ ๊ฒ์ ์กฐ์ฌํ์ต๋๋ค. FileOutputStream์ ์ด๋ป๊ฒ ๊ตฌ์ฑ๋์ด ์์ต๋๊น?"
"์ข์. ์ด๊ฒ ์ข ๋ด:"
๋ฐฉ๋ฒ | ๋ฉ์๋๊ฐ ์ํํ๋ ์์ |
---|---|
|
"์ด๊ฒ์ ์์ฑ์์ ๋๋ค. ์์ฑ๋ ๊ฐ์ฒด๊ฐ ๋ฐ์ดํฐ๋ฅผ ์ธ ๋์คํฌ์ ํ์ผ ์ด๋ฆ์ ์ง์ ํ ์ ์์ต๋๋ค." |
|
"์ด ๋ฉ์๋๋ ๋ค์ ๋ฐ์ดํธ๋ฅผ ์ฐ๊ณ ๋ฐ์ดํฐ๋ฅผ 1๋ฐ์ดํธ๋ก ์๋ฆ ๋๋ค." |
|
"๊ธฐ๋กํ ๋ฐ์ดํฐ๋ ๋จผ์ ๋ฉ๋ชจ๋ฆฌ์ ํฐ ๋ธ๋ก์ ์์ง๋ ๋ค์ ๋์คํฌ์๋ง ๊ธฐ๋ก๋๋ ๊ฒฝ์ฐ๊ฐ ๋ง์ต๋๋ค."
flush ๋ช ๋ น์ ์ ์ฅ๋์ง ์์ ๋ชจ๋ ์ ๋ณด๋ฅผ ๊ฐ์ ๋ก ๋์คํฌ์ ๊ธฐ๋กํฉ๋๋ค. |
|
"์ด ๋ฉ์๋๋ ์คํธ๋ฆผ์ ยซ๋ซ์ต๋๋คยป. ์คํธ๋ฆผ ์์
์ ๋ง์น๋ฉด ์ด ๋ฉ์๋๋ฅผ ํธ์ถํฉ๋๋ค." ๊ทธ๋ฐ ๋ค์ ๊ฐ์ฒด๋ ํ์ผ ๋ฑ์ ๋ซ๋ ๋ฐ ํ์ํ ์ ๋ฆฌ ์์ ์ ์ํํฉ๋๋ค. |
๋ ์ด์ ์คํธ๋ฆผ์ ๋ฐ์ดํฐ๋ฅผ ์ธ ์ ์์ผ๋ฉฐ ํ๋ฌ์๊ฐ ์๋์ผ๋ก ํธ์ถ๋ฉ๋๋ค.
"๊ทธ๊ฒ ๋ค์ผ?"
"๋ค, ์ค์ ๋ก ์ฐ๋ ๋ฐฉ๋ฒ์ ๋จ ํ๋๋ฟ์ ๋๋ค. ๋ฐ๋ก write()์ ๋๋ค. ํ ๋ฒ์ ํ ๋ฐ์ดํธ๋ง ์๋๋ค. ํ์ง๋ง ํ์ผ์ ์ํ๋ ๋งํผ ๋ง์ ์ ๋ณด๋ฅผ ์ธ ์ ์์ต๋๋ค."
ํ๋ก๊ทธ๋๋ฐ์ ํ๋์ ํฌ๊ณ ๋ณต์กํ ์์ ์ ์ฌ๋ฌ ๊ฐ์ ์์ ์์ ์ผ๋ก ๋๋๋ ๊ณผ์ ์ ๋๋ค. ๊ธฐ๋ณธ์ ์ผ๋ก ๋์ผํ ํ๋ก์ธ์ค๊ฐ ์ฌ๊ธฐ์์ ๋ฐ์ํฉ๋๋ค. ํฐ ๋ฐ์ดํฐ ๋ธ๋ก์ ์ฝ๊ณ ์ฐ๋ ์์ ์ ํ ๋ฒ์ ํ ๋ฐ์ดํธ์ฉ ๋ฐ์ดํธ ํฌ๊ธฐ์ ์ฝ๊ธฐ ๋ฐ ์ฐ๊ธฐ๋ก ๋๋ฉ๋๋ค.
๋ค์์ ์ด๋ฌํ ํด๋์ค๋ฅผ ์ฌ์ฉํ์ฌ ๋์คํฌ์ ํ์ผ์ ๋ณต์ฌํ๋ ๋ฐฉ๋ฒ์ ๋๋ค.
public static void main(String[] args) throws Exception
{
//Create a stream to read bytes from a file
FileInputStream inputStream = new FileInputStream("c:/data.txt");
//Create a stream to write bytes to a file
FileOutputStream outputStream = new FileOutputStream("c:/result.txt");
while (inputStream.available() > 0) //as long as there are unread bytes
{
int data = inputStream.read(); // Read the next byte into the data variable
outputStream.write(data); // and write it to the second stream
}
inputStream.close(); //Close both streams. We don't need them any more.
outputStream.close();
}
"๊ณ ๋ง์, Rishi. ๋๋์ด ์ด ์ฝ๋๊ฐ ์ค์ ๋ก ์ด๋ป๊ฒ ์๋ํ๋์ง ์ดํดํ์ด."