FileOutputStream에서 바이트 배열에 값을 입력시킨 후
바이트배열 by를 write한 경우이다.
package fileTest;
import java.io.File;
import java.io.FileOutputStream;
public class FileOutputStreamTest {
public static void main (String [] args) throws Exception{
byte [] by = new byte[]{'a','b','c'}; // 내가 원하는곳에 쓸 내용을 byte배열에 담는다.
File directory = new File("d:\\테스트중");
File file_name = new File (directory, "test1.txt"); //여긴 FileIntputStream과 다를게 없다.
if(!directory.isDirectory()){ //*중요* 디렉토리가 없을수도 있으므로 없다면
directory.mkdir(); 만들어주는 if문을 만든다.
}
FileOutputStream fos = new FileOutputStream(file_name,true);
fos.write(by);
fos.close();
}
}
--------------------------------String에 담은후 getBytes()메서드 이용 ----------------
package fileTest;
import java.io.File;
import java.io.FileOutputStream;
public class FileOutputStream2 {
public static void main (String [] args)throws Exception{
File directory = new File("d:\\테스트중");
File file_name = new File(directory,"test2.txt");
if(!directory.isDirectory()){
directory.mkdir();
}
FileOutputStream fos = new FileOutputStream(file_name,true);
String msg = "안녕하세요,김창호입니다.";
fos.write(msg.getBytes()); //String형 msg를 바이트로 바꾸어 줌.
fos.close();
}
}
-----------------------BufferedOutputStream 사용!!----------------
package fileTest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
public class BufferedOutputStreamTest {
public static void main( String [] args)throws Exception{
File directory = new File("d:\\테스트중");
File file_name = new File(directory,"test3.txt");
if(!directory.isDirectory()){
directory.mkdir();
}
FileOutputStream fos = new FileOutputStream(file_name,true);
BufferedOutputStream bos= new BufferedOutputStream(fos);
String msg = "dfdf안녕하세요,김창호입니다.";
bos.write(msg.getBytes());
bos.close();
}
}
------------------------------FileWriter--------------------------------
주의사항!!!! 쓰고싶은 메시지를 String형에 담고 write()를 해주기위해
char 배열로 형변환을 해줘야함 그것이 바로 toCharArray();
package fileTest;
import java.io.File;
import java.io.FileWriter;
public class FileWriterTest {
public static void main(String[] args) throws Exception {
File directory = new File("d:\\테스트중");
File file_name = new File(directory, "test4.txt");
if (!directory.isDirectory()) {
directory.mkdir();
}
FileWriter fw = new FileWriter(file_name,true);
String msg = "이야이오";
fw.write(msg.toCharArray()); //이런식으로 toCharArray() 외워라!!
fw.close();
}
}
-----------------BufferedWriter도 똑같음!!------------------------------------------
package fileTest;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
public class BufferedWriterTest {
public static void main(String[] args) throws Exception {
File directory = new File("d:\\테스트중");
File file_name = new File(directory, "test5.txt");
if (!directory.isDirectory()) {
directory.mkdir();
}
FileWriter fw = new FileWriter(file_name,true);
BufferedWriter bw = new BufferedWriter(fw);
String msg = "이야이오";
bw.write(msg.toCharArray()); //Char배열로 바꿔줘야함.
bw.close();
}
}