java的IO操作还不熟,以前学c,c++也没学好这一块。不过以前觉得从控制台输入还很简单,到java这里似乎变得麻烦了得定义一个BufferedReader引用,对象得写成new InputStreamReader(System.in),真是麻烦!
注意从控制台输入字符写到相应文件中的时候得关闭文件才能将数据写进去,关闭文件之前还应调用 flush()方法刷新该流的缓冲将输入的字符写入到文本中
注意几个方法:new FileWriter(new File(),true)表示追加写到文件中
BufferedWriter对象通过调用append方法追加,这种方法是在同一次打开操作过程中追加
class charStatic
{
public static void main(String[] args)
{
charStatic cs=new charStatic();
cs.WriteFile("abc.txt");
cs.ReadFile("abc.txt");
}
public void ReadFile(String path)//文件读取
{
File f=new File(path);
if(!f.exists())
{
System.out.print("文件不存在,将创建一个新文件");
try
{
f.createNewFile();
}
catch(Exception e)
{
System.out.println("文件创建失败");
}
}
try
{
BufferedReader r=new BufferedReader(new FileReader(f));
String c="";
String b="";
while((c=r.readLine())!=null)
{
b+=c;
}
System.out.println(b);
}
catch(IOException e)
{
System.out.println("读取文件失败!");
}
}
public void WriteFile(String path)
{
File f=new File(path);
try
{
BufferedWriter w=new BufferedWriter(new FileWriter(f,true));
BufferedReader cin=new BufferedReader(new InputStreamReader(System.in));
String c="";
while((c=cin.readLine()).length()!=0)
{
w.append(c);
}
w.newLine();
w.flush();
w.close();
}
catch(Exception e)
{
System.out.println("文件读取失败");
}
}
}
注意从控制台输入字符写到相应文件中的时候得关闭文件才能将数据写进去,关闭文件之前还应调用 flush()方法刷新该流的缓冲将输入的字符写入到文本中
注意几个方法:new FileWriter(new File(),true)表示追加写到文件中
BufferedWriter对象通过调用append方法追加,这种方法是在同一次打开操作过程中追加
class charStatic
{
public static void main(String[] args)
{
charStatic cs=new charStatic();
cs.WriteFile("abc.txt");
cs.ReadFile("abc.txt");
}
public void ReadFile(String path)//文件读取
{
File f=new File(path);
if(!f.exists())
{
System.out.print("文件不存在,将创建一个新文件");
try
{
f.createNewFile();
}
catch(Exception e)
{
System.out.println("文件创建失败");
}
}
try
{
BufferedReader r=new BufferedReader(new FileReader(f));
String c="";
String b="";
while((c=r.readLine())!=null)
{
b+=c;
}
System.out.println(b);
}
catch(IOException e)
{
System.out.println("读取文件失败!");
}
}
public void WriteFile(String path)
{
File f=new File(path);
try
{
BufferedWriter w=new BufferedWriter(new FileWriter(f,true));
BufferedReader cin=new BufferedReader(new InputStreamReader(System.in));
String c="";
while((c=cin.readLine()).length()!=0)
{
w.append(c);
}
w.newLine();
w.flush();
w.close();
}
catch(Exception e)
{
System.out.println("文件读取失败");
}
}
}

被折叠的 条评论
为什么被折叠?



