本地文件java常用操作

来源:互联网 发布:家装网络销售好做吗 编辑:程序博客网 时间:2024/06/02 03:05

每次读取一行,写文件用的是BufferWriter


package cn.mastercom.filterSpark;

import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* Created by Administrator on 2017/3/18.
*/

public class GenerateConfXml {
public static void main(String[] args) {
FileInputStream fis = null;
InputStreamReader isr = null;
BufferedReader br = null ;//用于包装InputStreamReader,提高处理性能。因为BufferedReader有缓冲的,而InputStreamReader没有。
String str ="";
String str1="";

try {
fis = new FileInputStream("conf_test/TB_MODEL_SIGNAL_SAMPLE.sql");
isr = new InputStreamReader(fis);
br = new BufferedReader(isr);// 从字符输入流中读取文件中的内容,封装了一个new InputStreamReader的对象
while ((str = br.readLine())!=null){
str1+=str.trim()+"qqqq"+"\n";
}
System.out.println(str1);

} catch (Exception e) {
e.printStackTrace();
}

try {
br.close();
isr.close();
fis.close();
// 关闭的时候最好按照先后顺序关闭最后开的先关闭所以先关s,再关n,最后关m
} catch (IOException e) {
e.printStackTrace();
}



File file = new File("conf_test/TB_MODEL_SIGNAL_SAMPLE.xml");
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}

FileWriter fw = null;
try {
//这里如果是 FileWriter fw = new FileWriter(file.getAbsoluteFile(),true);, 那么是在后面添加
fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?> \n");
bw.write("<table> \n");
bw.write(xml);
bw.write("</table>");
bw.close();
}catch (IOException e) {
e.printStackTrace();
}


}

private static String attrTransform(String fieldOrAttr) {
if("[varchar]".equals(fieldOrAttr)){
fieldOrAttr = "string";
}else if("[bigint]".equals(fieldOrAttr)){
fieldOrAttr = "long";
}else if("[smallint]".equals(fieldOrAttr)||"[tinyint]".equals(fieldOrAttr)){
fieldOrAttr = "int";
}
return fieldOrAttr;
}
}

另外一种写的方式,FileOutStrem+StringBuffer的方式,可以多次写入

public class TestFileIo {
public static void main(String[] args) {
File file=new File("G:\\sqldata2\\result\\out1358\\test.txt");
if(!file.exists())
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
FileOutputStream out= null;
try {
out = new FileOutputStream(file,true);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
StringBuffer sb=new StringBuffer();
sb.append("这是第"+1+"行:前面介绍的各种方法都不关用,为什么总是奇怪的问题 "+"\n");
try {
out.write(sb.toString().getBytes("utf-8"));
} catch (IOException e) {
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}

}

按照行读取文件内容

/**
* 以行为单位读取文件,常用于读面向行的格式化文件
*/

public static void readFileByLines(String fileName) {
File file = new File(fileName);
BufferedReader reader = null;
try {
System.out.println("以行为单位读取文件内容,一次读一整行:");
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
// 一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
// 显示行号
System.out.println("line " + line + ": " + tempString);
line++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}

按字节读取文件内容

/**
* 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
*/

public static void readFileByBytes(String fileName) {
File file = new File(fileName);
InputStream in = null;
try {
System.out.println("以字节为单位读取文件内容,一次读一个字节:");
// 一次读一个字节
in = new FileInputStream(file);
int tempbyte;
while ((tempbyte = in.read()) != -1) {
System.out.write(tempbyte);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
return;
}
try {
System.out.println("以字节为单位读取文件内容,一次读多个字节:");
// 一次读多个字节
byte[] tempbytes = new byte[100];
int byteread = 0;
in = new FileInputStream(fileName);
ReadFromFile.showAvailableBytes(in);
// 读入多个字节到字节数组中,byteread为一次读入的字节数
while ((byteread = in.read(tempbytes)) != -1) {
System.out.write(tempbytes, 0, byteread);
}
} catch (Exception e1) {
e1.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e1) {
}
}
}
}

按字符读取文件内容

/**
* 以字符为单位读取文件,常用于读文本,数字等类型的文件
*/

public static void readFileByChars(String fileName) {
File file = new File(fileName);
Reader reader = null;
try {
System.out.println("以字符为单位读取文件内容,一次读一个字节:");
// 一次读一个字符
reader = new InputStreamReader(new FileInputStream(file));
int tempchar;
while ((tempchar = reader.read()) != -1) {
// 对于windows下,\r\n这两个字符在一起时,表示一个换行。
// 但如果这两个字符分开显示时,会换两次行。
// 因此,屏蔽掉\r,或者屏蔽\n。否则,将会多出很多空行。
if (((char) tempchar) != '\r') {
System.out.print((char) tempchar);
}
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
System.out.println("以字符为单位读取文件内容,一次读多个字节:");
// 一次读多个字符
char[] tempchars = new char[30];
int charread = 0;
reader = new InputStreamReader(new FileInputStream(fileName));
// 读入多个字符到字符数组中,charread为一次读取字符数
while ((charread = reader.read(tempchars)) != -1) {
// 同样屏蔽掉\r不显示
if ((charread == tempchars.length)
&& (tempchars[tempchars.length - 1] != '\r')) {
System.out.print(tempchars);
} else {
for (int i = 0; i < charread; i++) {
if (tempchars[i] == '\r') {
continue;
} else {
System.out.print(tempchars[i]);
}
}
}
}

} catch (Exception e1) {
e1.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}

java读写压缩文件

.gz文件的读写

读取 
其实就是多了一步,就是把用InputStreamReader 对 FileInputStream进行了一层包装

public static void main(String[] args) throws Exception {
FileInputStream fis =new FileInputStream("path");
GZIPInputStream gzipInputStream = new GZIPInputStream(fis);
InputStreamReader in = new InputStreamReader(gzipInputStream);
BufferedReader br = new BufferedReader(in);
String str="";
while ((str=br.readLine())!=null){
String[] split = str.split("\t");
System.out.println(split[0]);
}
//关闭流,参考前面的,这里就不写了
}

 
相比于没有压缩的,就多了一步 GZIPOutputStream 对 FileOutputStream的包装

    public static void saveToGZFiles(String text, File file) {
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
FileOutputStream out= null;
out = new FileOutputStream(file,true);
GZIPOutputStream gzipOut = new GZIPOutputStream(out);
StringBuffer sb=new StringBuffer();
sb.append(text);
gzipOut.write(sb.toString().getBytes("utf-8"));
// out.close();
gzipOut.close();
}catch (Exception e){
e.printStackTrace();
}
}

读取文件夹下的所有文件

String path="E:\\datatest\\input\\TB_CQTSIGNAL_SAMPLE_01_170221";
File files = new File(path);
if(files.isFile()){
//说明是文件
System.out.println("文件");
System.out.println("path=" + files.getPath());
System.out.println("absolutepath=" + files.getAbsolutePath());
System.out.println("name=" + files.getName());
}
if(files.isDirectory()){
//说明是文件夹
String[] filelist = files.list();
for (int j = 0; j < filelist.length; j++){
//调用上面的读取方法
fis = new FileInputStream(path+"\\"+filelist[i]);
....
}
}

复制文件

以文件流的方式复制文件

 public void copyFile(String src,String dest) throws IOException...{
FileInputStream in=new FileInputStream(src);
File file=new File(dest);
if(!file.exists())
file.createNewFile();
FileOutputStream out=new FileOutputStream(file);
int c;
byte buffer[]=new byte[1024];
while((c=in.read(buffer))!=-1)...{
for(int i=0;i<c;i++)
out.write(buffer[i]);
}
in.close();
out.close();
}

创建文件夹

public void createDir(String path)...{
File dir=new File(path);
if(!dir.exists())
dir.mkdir();
}

创建文件

public void createFile(String path,String filename) throws IOException...{
File file=new File(path+"/"+filename);
if(!file.exists())
file.createNewFile();
}

删除文件

public void delFile(String path,String filename)...{
File file=new File(path+"/"+filename);
if(file.exists()&&file.isFile())
file.delete();
}
原创粉丝点击