📄 readandwrite.java
字号:
package handlingOfFile;
public class ReadAndWrite
{
public static void ReadFileByBufferedStream(String srcfile, String dstfile)
{ //output to console may have wrong char, such as ??%%$$
try
{
int i = 0;
byte[] data;
String str;
int buflen = 32;
data = new byte[buflen];
java.io.FileInputStream fi = new java.io.FileInputStream(srcfile);
java.io.BufferedInputStream bfi = new java.io.BufferedInputStream(fi, buflen);
java.io.FileOutputStream fo = new java.io.FileOutputStream(dstfile);
java.io.BufferedOutputStream bfo = new java.io.BufferedOutputStream(fo);
while(bfi.read(data) != -1) //entire file
{
i++;
str = new String(data);
bfo.write(data);
bfo.flush();
System.out.print(str); // console may be
}//while
bfo.flush();
bfi.close();
bfo.close();
}//try
catch(Exception e)
{
System.err.println("error found : ReadFile( "+srcfile+")");
e.printStackTrace();
}//catch
}//ReadFile
//-----------------------------------------------------------------
public static String ReadFileByBuffer(String url)
{
String str2 = new String();
try
{
java.io.LineNumberReader lnr = new java.io.LineNumberReader(new java.io.FileReader(url));
String str;
for(str = lnr.readLine(); str != null; str = lnr.readLine())
{
str2 += str;
str2 += "\n";
}//for
lnr.close();
}//try
catch(java.io.IOException e)
{
System.out.println("error found : ReadFileByReaderBuffer("+url+"). can't find file: "+url);
//e.printStackTrace();
}//catch
return str2;
}
//-----------------------------------------------------------------
public static boolean WriteFileByBuffer(String url, String content)
{ //write a file, without checking if the file: url has been existed.
try
{
/*java.io.File f = new java.io.File(url);
if(f.exists())
{
System.err.println("filel "+ url + " is already exist!");
System.out.println("Change a name,please input Y/y");
System.out.println("Go On Write with the existed name, please input N/n");
}*/
java.io.BufferedWriter bw = new java.io.BufferedWriter(new java.io.FileWriter(url));
String [] str = content.split("\n");
for(int i = 0; i < str.length; i++)
{
bw.write(str[i]);
bw.newLine();
bw.flush();
}
bw.flush(); //if no flush(), you may not find the text in the file
bw.close();
}//try
catch(java.io.IOException e)
{
System.err.println("error found : WriteFileByReaderBuffer("+url+")");
e.printStackTrace();
return false;
}//catch
return true;
}
//-----------------------------------------------------------------
public static void main(String[] args)
{
java.awt.EventQueue.invokeLater
(
new Runnable()
{
public void run()
{
if(WriteFileByBuffer("test2.txt","hello\n"+"go\n"))
{
System.out.println(ReadFileByBuffer("test2.txt"));
}
}
}
); //java.awt.EventQueue.invokeLater(---
}//main()
}//ReadAndWrite
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -