您的位置:首页 > 编程语言 > Java开发

java 文件基本操作总结

2014-04-18 11:02 579 查看
这里对java对文件的基本操作进行了总结,代码实现了最常用的几种操作,其中包括有:控制台输入,文件读取,文件写入,还有文件拷贝

代码贴上:

/*
* 控制台输入一行
*/
public static String consoleInput()
{
BufferedReader reader = new BufferedReader(
new InputStreamReader(System.in));
String line = null;
try
{
line = reader.readLine();
} catch (IOException e)
{
e.printStackTrace();
} finally
{
if(reader != null)
{
try
{
reader.close();
reader = null;
} catch (IOException e)
{
e.printStackTrace();
}
}
}
return line;
}

/*
* 文件写入操作
* 按照系统默认编码像文件中写入一行
*/
public static void writeLine(String str, String filePath)
{
BufferedWriter bw = null;

try
{
bw = new BufferedWriter(new FileWriter(filePath));
bw.write(str);
bw.newLine();
} catch (IOException e)
{
e.printStackTrace();
} finally
{
if(bw != null)
{
try
{
bw.close();
bw = null;
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}

/*
* 文件的写入操作
* 按照指定编码格式写入文件
*/
public static void writeLine_setChar(String str)
{
String filePath = "a.txt";
BufferedWriter bw = null;

//设置编码格式
//String charSet = System.getProperty("file.encoding");
String setChar = "utf-8";

try
{
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath, true), setChar));
bw.write(str);
bw.newLine();
} catch (IOException e)
{
e.printStackTrace();
} finally
{
if(bw != null)
{
try
{
bw.close();
bw = null;
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}

/*
* 文件的读取操作
* 把一个文件中的内容输出到控制台上
*/
public static void readFileToConsole(String filePath)
{
BufferedReader br = null;
try
{
//按照系统默认编码格式读取文件
//br = new BufferedReader(new FileReader(filePath));

//按照指定的编码格式读取文件
String charSet = "gbk";
br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), charSet));
String line;
while((line = br.readLine()) != null)
{
System.out.println(line);
}

} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} finally
{
if(br != null)
{
try
{
br.close();
br = null;
} catch (Exception e2)
{
System.out.println(e2.getMessage());
}
}
}
}

public static void copyFile(String source, String destination)
{
BufferedReader br = null;
BufferedWriter bw = null;

try
{
String charSet = "utf-8";
br = new BufferedReader(new InputStreamReader(new FileInputStream(source), charSet));
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(destination), charSet));
String line;
while((line = br.readLine()) != null)
{
bw.write(line);
bw.newLine();
}
} catch (IOException e)
{
e.printStackTrace();
} finally
{
try
{
if(br != null)
{
br.close();
br = null;
}
if(bw != null )
{
bw.close();
bw = null;
}
} catch (IOException e2)
{
// TODO: handle exception
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java io 文件操作