import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class FileIO {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// 1.创建文件夹 mkdir
// 如果路径存在,才可以通过该方法创建文件夹。。。mkdirs路径不存在也可以通过这个方法创建,先创建路径再创建文件夹
File myFolderPath = new File("D:\\MyEclipse2013Work\\Test\\test");
try {
if (!myFolderPath.exists()) {
myFolderPath.mkdir();
}
} catch (Exception e) {
System.out.println("新建目录操作出错");
e.printStackTrace();
}
// 2. 创建文件 FileWrite 和PrintWrite 的区别需要注意
File myFilePathFile = new File("test.txt");
try {
if (!myFilePathFile.exists()) {
myFilePathFile.createNewFile();
}
FileWriter resultFile = new FileWriter(myFilePathFile);
PrintWriter myFile = new PrintWriter(resultFile);
myFile.println("新建文件操作");
myFile.println("新建文件操作");
myFile.println("新建文件操作");
myFile.println("新建文件操作");
myFile.write("sss", 1, 1);
myFile.println("新建文件操作");
resultFile.write("sssssssssssss");
resultFile.close();
} catch (Exception e) {
// TODO: handle exception
System.out.println("新建文件操作出错");
e.printStackTrace();
}
// 3. FileWrite 结合BufferedWriter打印文本换行
TestBufferedWriter();
// 4.获得当前工程的路径
File directory = new File("");// 参数为空
String courseFile = directory.getCanonicalPath();
System.out.println(courseFile);
}
public static void TestBufferedWriter() {
try {
String filePath = "test1.txt";
File myFile = new File(filePath);
if (!myFile.exists()) {
myFile.createNewFile();
}
FileWriter resultFile = new FileWriter(myFile);
BufferedWriter buffer = new BufferedWriter(resultFile);
String fileContent = "This is my name./n we are isoftsotne.com /n chinesebillboy at here。/n";
String contentString = "";
int flag = 0;
boolean isGO = true;
while ((flag = fileContent.indexOf("/n")) != -1 && isGO) {
contentString = fileContent.substring(0, flag);
buffer.write(contentString);
buffer.newLine();
buffer.flush();
if (flag + 2 >= fileContent.length()) {
isGO = false;
} else {
fileContent = fileContent.substring(flag + 2);
}
}
buffer.flush();
resultFile.flush();
buffer.close();
resultFile.close();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
}
}
}