之前看IO输入输出觉得没啥用,开始工作后才意识到其重要性,故边工作边二次学习,整理如下。
输入输出整体架构如下:
1 访问文件和目录
public static void TextIO() throws IOException{
File file4=new File("D:/dema");//绝对路径
file4.mkdir();//创建一个目录
System.out.println("创建文件夹:"+file4.getName());
System.out.println("文件夹路径:"+file4.getAbsolutePath());
File file3=new File(file4.getAbsolutePath()+"/demaxiya.txt");
if(file3!=null){
file3.createNewFile();//创建一个文件
System.out.println("创建文件:"+file3.getName());
System.out.println("文件路径:"+file3.getAbsolutePath());
System.out.println("该文件的父目录:"+file3.getParent());
}
}
2 文件的读和写
public static void ReadText() throws IOException{
String relativelyPath=System.getProperty("user.dir"); //获取当前项目的路径
System.out.println(relativelyPath);
FileInputStream fileInputStream=new FileInputStream(relativelyPath+"/src/IOExample.java");
byte[] buff=new byte[1024];//一次从中读取1024分字节
//byte[] b=new byte[(int) fileInputStream.length()];分配指定的内存大小
int hasRead=0;//读取的字节量
while((hasRead=fileInputStream.read(buff))>0){
System.out.println(new String(buff, 0, hasRead));
}
fileInputStream.close();//关闭
}
public static void CopyFile() throws IOException{
String relativelyPath=System.getProperty("user.dir"); //获取当前项目的路径
System.out.println(relativelyPath);
FileInputStream fileInputStream=new FileInputStream(relativelyPath+"/src/IOExample.java");
FileOutputStream fileOutputStream=new FileOutputStream("D:/dema.txt");
byte[] buff=new byte[1024];
Integer hasRead=0;
while((hasRead=fileInputStream.read(buff))>0){//读取到数字 中,直到读取完
fileOutputStream.write(buff,0,hasRead);//从0开始读取hasRead个buff中的字符到指定输出流中
}
fileOutputStream.close();//关闭
fileInputStream.close();//关闭
}
字符流复制文件:
public static void textReader() throws IOException{
File file=new File("C:"+File.separator+"demo.txt");
if(!file.exists()){//判读该文件是否存在
file.createNewFile();//创建一个文件
}
//读取字符
Reader reader=new FileReader(file);
char[] buff=new char[(int)file.length()];
int len=reader.read(buff);
//输出字符
Writer writer=new FileWriter(file);
writer.write(buff);
}
byte[] bytes = new byte[1024];// 一次性读取1024个字节
inputStream = request.getInputStream();
outputStream = new FileOutputStream("D:\\" + "a.jpg");
Integer hasRead = 0;
while ((hasRead = inputStream.read(bytes)) > 0) {
outputStream.write(bytes, 0, hasRead);
}
3 对象的序列化一
public static void SerializOutPutExample() throws IOException, Exception{
//处理流,建立在其他节点流的基础之上
ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("./src/SerializExample.txt"));//.为当前目录下,即相对路径。为项目下。
Person person=new Person();
person.setId(1);
person.setName("demaxiya");
person.setAge(1);
oos.writeObject(person);//将对象写入输出流
oos.close();
}
public static void SerializInPutExample() throws Exception, IOException{
ObjectInputStream ois=new ObjectInputStream(new FileInputStream("./src/SerializExample.txt"));//
Person person=(Person)ois.readObject();//读取对象
System.out.println(person.getId());
System.out.println(person.getName());
}
4 对象的序列化二
/**
* 实现对象流实现序列化
* @throws FileNotFoundException
* @throws IOException
* @throws ClassNotFoundException
*/
public static void objectOutStream() throws FileNotFoundException, IOException, ClassNotFoundException{
//创建一个对象
User user=new User();
user.setId(1);
user.setName("dema");
user.setPassword("123");
//创建一个输出流
ObjectOutputStream objectOutputStream=new ObjectOutputStream(new FileOutputStream("temp.txt"));
//将一个对象写入输出流
objectOutputStream.writeObject(user);
//创建一个输入流
ObjectInputStream objectInputStream=new ObjectInputStream(new FileInputStream("temp.txt"));
//读取流中的对象,将其强转为User对象
User user2=(User)objectInputStream.readObject();
System.out.println(user2.getName());
}
5 访问目录下的所有文件:
/**
* 读取某文件夹下的所有文件
* @param dir
* @throws Exception
*/
public static void showAllFiles(File dir) throws Exception {
File[] fs = dir.listFiles();
for (int i = 0; i < fs.length; i++) {
if (fs[i].isDirectory()) {//是目录
try {
showAllFiles(fs[i]);//访问该目录下
} catch (Exception e) {
e.getMessage();
}
} else {//为文件
System.out.println(fs[i].getName());
}
}
}
6 java读取execl文件
下载jar包:jxl.jar
/**
* 读取Execl文档
* @throws IOException
* @throws BiffException
*/
public static void readExecl() throws IOException, BiffException{
FileInputStream stream=new FileInputStream("D://dema1.xls");
Workbook workbook=Workbook.getWorkbook(stream);
//获取第一个sheet文档
Sheet readSheet=workbook.getSheet(0);
//总行数
int col=readSheet.getColumns();
//总列数
int row=readSheet.getRows();
for(int a=0;a<col;a++){//列数
for(int b=0;b<row;b++){//行数
Cell cell=readSheet.getCell(b, a);
System.out.print(cell.getContents());
}
System.out.println();
}
}
7 word转pdf
参考博客:http://blog.csdn.net/u011763190/article/details/51017682
word转pdf
/**
* word转pdf
*/
public static void wordToPdf() {
try {
long start = System.currentTimeMillis();
InputStream is = new FileInputStream(new File("D:\\dema3.docx"));
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(is);
List sections = wordMLPackage.getDocumentModel().getSections();
for (int i = 0; i < sections.size(); i++) {
System.out.println("sections Size" + sections.size());
wordMLPackage.getDocumentModel().getSections().get(i).getPageDimensions().setHeaderExtent(3000);
}
Mapper fontMapper = new IdentityPlusMapper();
PhysicalFont font = PhysicalFonts.getPhysicalFonts().get("Comic Sans MS");
fontMapper.getFontMappings().put("Algerian", font);
wordMLPackage.setFontMapper(fontMapper);
PdfSettings pdfSettings = new PdfSettings();
PdfConversion conversion = new Conversion(wordMLPackage);
OutputStream out = new FileOutputStream(new File("D:\\javadomain.pdf"));
conversion.output(out, pdfSettings);
System.err.println("Time taken to Generate pdf " + (System.currentTimeMillis() - start) + "ms");
} catch (Exception e) {
e.printStackTrace();
}
}
架包:
/Text03/lib/avalon-framework-api-4.3.1.jar
/Text03/lib/avalon-framework-impl-4.3.1.jar
/Text03/lib/batik-util-1.9.1.jar
/Text03/lib/commons-io-2.4.jar
/Text03/lib/commons-logging-1.2.jar
/Text03/lib/commons-logging-api-1.1.jar
/Text03/lib/docx4j-2.7.1.jar
/Text03/lib/fop-1.0.jar
/Text03/lib/log4j-1.2.17.jar
/Text03/lib/serializer-2.7.1.jar
/Text03/lib/slf4j-log4j12-1.7.21.jar
/Text03/lib/xalan-2.7.1.jar
/Text03/lib/xmlbeans-2.3.0.jar
/Text03/lib/xmlgraphics-commons-1.4.jar
pom添加:
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j</artifactId>
<version>2.7.1</version>
</dependency>
<dependency>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>batik-util</artifactId>
<version>1.9.1</version>
</dependency>
8 控制台输入输出
public static void getConsoleInput(){
BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
String str=null;
try {
str = reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(str);
}
线上出现一个Bug,文件上传后存储到临时的目录中,后来在线上系统中查看该目录下,发现存在很多文件,没有被删除,百度了一下,发现是最基本的文件流没有关闭,
https://www.cnblogs.com/longshiyVip/p/4960306.html
自己写了一个Demo:
public static void main(String[] args) {
// System.out.println(test01());
// System.out.println(test02());
File file1 = new File("D:\\uploadTempBasePath\\1.zip");
File file2 = new File("D:\\uploadTempBasePath\\2.zip");
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = new FileInputStream(file1);
outputStream = new FileOutputStream(file2);
byte[] buff = new byte[1024];
int hasReadSize = 0;
while ((hasReadSize = inputStream.read(buff)) > 0) {
outputStream.write(buff, 0, hasReadSize);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
//测试不关闭文件流能否关删除件
/*if (outputStream != null) {
outputStream.close();
}*/
} catch (IOException e) {
e.printStackTrace();
}
}
file2.delete();
}
打开如图中的注释,能删除文件,但是注释掉代码中的注释,就不能删除,因为文件流该改文件的占用,用完没有关闭文件流。