반응형
Java로 개발 시에 File을 열고 쓰는 등의 기초 작업에 대하여 다뤄보겠습니다.
/**
* Created by 진우 on 2016-07-19.
*/
public class MyManageTextFile {
public static void main(String[] args) {
MyManageTextFile managerTest = new MyManageTextFile();
int count = 10;
String path = "C:\\" + separator + "jinwoo.txt";
//managerTest.writeFile(path, numberCount);
managerTest.readFile(path);
System.out.println();
managerTest.readFileScanner(path);
}
public void writeFile(String fileName, int count) {
FileWriter fw = null;
BufferedWriter bw = null;
try {
fw = new FileWriter(fileName);
bw = new BufferedWriter(fw);
for(int loop=0; loop<=count; loop++) {
bw.write(Integer.toString(loop));
bw.newLine();
}
System.out.println("Write Success!");
} catch(IOException ioe) {
ioe.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
} finally {
if(bw != null) {
try {
bw.close();
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
if(fw != null) {
try {
fw.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
public void readFile(String fileName) {
FileReader fr = null;
BufferedReader br = null;
try {
fr = new FileReader(fileName);
br = new BufferedReader(fr);
String data;
while((data = br.readLine()) != null) {
System.out.println(data);
}
System.out.println("Read Success!");
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if(br != null) {
try {
br.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
if(fr != null) {
try {
fr.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
public void readFileScanner(String fileName) {
File file = new File(fileName);
Scanner sc = null;
try {
sc = new Scanner(file);
while(sc.hasNextLine()) {
System.out.println(sc.nextLine());
}
System.out.println("Read Scanner Success!");
} catch (FileNotFoundException fe) {
fe.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if(sc != null) {
sc.close();
}
}
}
}
반응형
'Programming > JAVA' 카테고리의 다른 글
JavaAPI(9) - Java IO(File Test(2)) (0) | 2016.07.19 |
---|---|
JavaAPI(7) - Java Collection (Set Test) (0) | 2016.07.17 |
JavaAPI(6) - Java Collection (Queue Test) (0) | 2016.07.17 |
JavaAPI(5) - Java Collection (Map Test) (0) | 2016.07.17 |
JavaAPI(4) - Java Collection(ArrayList, Stack Test) (0) | 2016.07.17 |
WRITTEN BY
,