【建文件夹下的txt文件,并且按行写数据】
public class test1 {
public static void main(String[] args) throws IOException {
String directory="D:";
String fileName="myFile.txt";
File f=new File(directory,fileName);
//判断D盘是否含有myFile.txt文件
if(f.exists()){
System.out.println(f.getAbsolutePath());
System.out.println(f.getName());
System.out.println(f.length());
//写操作
FileWriter fw = new FileWriter(f,true); //设置成true就是追加
fw.write("ee");
fw.write("\r\n");//换行写入
fw.close();
System.out.println(f.length());
}else{
//目录中没有myFile.txt的文件,先创建文件所在的目录
f.getParentFile().mkdirs();
try{
//创建新文件
f.createNewFile();
//写操作
FileWriter fw = new FileWriter(f,true); //设置成true就是追加
fw.write("ee");
fw.write("\r\n");
fw.flush();
fw.close();
System.out.println(f.length());
}catch(IOException e){
System.out.println("创建新文件时出现了错误。。。");
e.printStackTrace();
}
}
}
}
【把txt文件按行形式读出来】
public class read {
public static void main(String[] args) throws IOException {
//读操作
String encoding="GBK";
File f = new File("d:/myFile.txt");
if(f.isFile() && f.exists()){
InputStreamReader read=new InputStreamReader(new FileInputStream(f), encoding);
BufferedReader bufferedreader = new BufferedReader(read);
String lineTXT=null;
while((lineTXT = bufferedreader.readLine()) !=null){
System.out.println(lineTXT.toString().trim());
}
read.close();
}else{
System.out.println("找不到指定的文件!");
}
}
}
public class test1 {
public static void main(String[] args) throws IOException {
String directory="D:";
String fileName="myFile.txt";
File f=new File(directory,fileName);
//判断D盘是否含有myFile.txt文件
if(f.exists()){
System.out.println(f.getAbsolutePath());
System.out.println(f.getName());
System.out.println(f.length());
//写操作
FileWriter fw = new FileWriter(f,true); //设置成true就是追加
fw.write("ee");
fw.write("\r\n");//换行写入
fw.close();
System.out.println(f.length());
}else{
//目录中没有myFile.txt的文件,先创建文件所在的目录
f.getParentFile().mkdirs();
try{
//创建新文件
f.createNewFile();
//写操作
FileWriter fw = new FileWriter(f,true); //设置成true就是追加
fw.write("ee");
fw.write("\r\n");
fw.flush();
fw.close();
System.out.println(f.length());
}catch(IOException e){
System.out.println("创建新文件时出现了错误。。。");
e.printStackTrace();
}
}
}
}
【把txt文件按行形式读出来】
public class read {
public static void main(String[] args) throws IOException {
//读操作
String encoding="GBK";
File f = new File("d:/myFile.txt");
if(f.isFile() && f.exists()){
InputStreamReader read=new InputStreamReader(new FileInputStream(f), encoding);
BufferedReader bufferedreader = new BufferedReader(read);
String lineTXT=null;
while((lineTXT = bufferedreader.readLine()) !=null){
System.out.println(lineTXT.toString().trim());
}
read.close();
}else{
System.out.println("找不到指定的文件!");
}
}
}