发现工作有些不可避免的重复工作,有时候量还比较大,自己就写个工具类,自动生成代码,当然还有一部分是没法避免的。
选择一种读文件和写文件的方式以后有需要的没有特别要求就用这一种。
package test1;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;
public class DemoIO {
public static void main(String[] args) throws Exception {
File file = new File("D:\\demoIo.txt");
if(!file.exists()){
file.createNewFile();
}
write1();
read();
//write2();
}
static void read() throws Exception{
String fileName="D:"+File.separator+"demoIo.txt";
File f=new File(fileName);
InputStream in=new FileInputStream(f);
byte[] b=new byte[(int)f.length()];
for (int i = 0; i < b.length; i++) {
b[i]=(byte)in.read();
}
in.close();
System.out.println(new String(b));
}
static void write1() throws Exception{
File file = new File("D:\\demoIo.txt");
OutputStream out =new FileOutputStream(file);
// OutputStream out =new FileOutputStream(file,true);//向文件中追加内容
String str="你好kevin\r\n";
byte[] b=str.getBytes();
out.write(b);
String str2="你好kevin2";
out.write(str2.getBytes());
out.close();
}
static void write2() throws IOException{
String fileName="D:"+File.separator+"demoIo.txt";
File f=new File(fileName);
Writer out =new FileWriter(f);
String str="你好kevin3";
out.write(str);
out.close();
}
}
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringUtils {
public static String replaceBlank(String str) {
String dest = "";
if (str!=null) {
Pattern p = Pattern.compile("\\s*|\t|\r|\n");
Matcher m = p.matcher(str);
dest = m.replaceAll("");
}
return dest;
}
public static void main(String[] args) {
System.out.println(StringUtils.replaceBlank("just do it!"));
}
/*-----------------------------------
String s = "你要去除的字符串";
1.去除空格:s = s.replace('\\s','');
2.去除回车:s = s.replace('\n','');
这样也可以把空格和回车去掉,其他也可以照这样做。
注:\n 回车(\u000a)
\t 水平制表符(\u0009)
\s 空格(\u0008)
\r 换行(\u000d)*/
}