1,程序给你免费试用5次,之后不给你玩了
package javaBase.io.others;
import java.io.*;
import java.util.*;
/*
* 程序给你免费试用5次,之后不给你玩了
*/
public class BetaPrograme {
public static void main(String[] args) throws IOException {
File file = new File("sys.properties");//用File类
if(!file.exists())
file.createNewFile();//文件不存在就创建一个
InputStream in = new FileInputStream(file);//读取流
Properties prop = new Properties();
prop.load(in);
int count = 0;//试用次数
String value = prop.getProperty("times");
if(value!=null){
count = Integer.parseInt(value);
if(count>=5){
System.out.println("您好,您的试用次数已到,请付费!");
return;
}
}
count++;
prop.setProperty("times", count+"");
//写入文件中
OutputStream out = new FileOutputStream(file);
prop.store(out, "");
out.close();
in.close();
}
}
2,将几个文本文件合成一个文件
package javaBase.io;
import java.io.*;
import java.util.Enumeration;
import java.util.Vector;//(ArrayList非线程安全)
/*
* 将3个文本文件合成一个文本文件
*/
public class MergeText {
public static void main(String[] args) throws IOException {
Vector<FileInputStream> v = new Vector<FileInputStream>();
v.add(new FileInputStream("1.txt"));
v.add(new FileInputStream("2.txt"));
v.add(new FileInputStream("3.txt"));
Enumeration<FileInputStream> en = v.elements();
SequenceInputStream sin = new SequenceInputStream(en);//合并流
FileOutputStream out = new FileOutputStream("4.txt");
byte[] buff = new byte[1024];
int len = 0;
while((len = sin.read(buff))!=-1){
out.write(buff,0,len);
}
out.close();
sin.close();
}
}
3,文件分割及合并
package javaBase.io;
import java.io.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
/*
* 分割文件(媒体文件)然后还原
*/
public class SplitFile {
public static void main(String[] args) throws IOException {
split();
merge();
}
/*
* 分割文件,最大为1M
*/
public static void split() throws IOException{
FileInputStream in = new FileInputStream("man.mp3");
FileOutputStream out = null;
byte[] buff = new byte[1024*1024];//1M 每读取1M写入文件
int len = 0;
int count = 1;
while((len = in.read(buff))!=-1){
out = new FileOutputStream("man"+(count++)+".part");
out.write(buff,0,len);//仅写入有效数据
out.close();
}
in.close();
}
/*
* 合并文件
*/
public static void merge() throws IOException{
ArrayList<FileInputStream> list = new ArrayList<FileInputStream>();
for(int i=1;i<=4;i++){//总共有4个文件
list.add(new FileInputStream("man"+i+".part"));
}
//vector可以直接调用elements()方法变成enumeration;
//ArrayList用迭代器:
final Iterator<FileInputStream> it = list.iterator();//匿名内部类要使用,所以用final
Enumeration<FileInputStream> en = new Enumeration<FileInputStream>() {
@Override
public FileInputStream nextElement() {
return it.next();
}
@Override
public boolean hasMoreElements() {
return it.hasNext();
}
};
//合并流
SequenceInputStream sin = new SequenceInputStream(en);
FileOutputStream out = new FileOutputStream("man_merge.mp3");
byte[] buff = new byte[1024*1024];//这里只有1M,若是太大的话会内存溢出,可以用循环每100M新建一个输出流
int len = 0;
while((len = sin.read(buff))!=-1){
out.write(buff,0,len);
}
out.close();
sin.close();
}
}