肿瘤康复网,内容丰富有趣,生活中的好帮手!
肿瘤康复网 > 信号转化java_Java基础知识回顾-7

信号转化java_Java基础知识回顾-7

时间:2020-01-13 13:48:39

相关推荐

1、ByteArrayInputStream、ByteArrayOutputStream

Stringstr="ZHANGSAN";

//System.out.println(str.toLowerCase());

ByteArrayInputStreaminputStream=newByteArrayInputStream(str.getBytes());

ByteArrayOutputStreamoutputStream=newByteArrayOutputStream();

intb;

while((b=inputStream.read())!=-1){

charlowerCase=Character.toLowerCase((char)b);

outputStream.write(lowerCase);

}

byte[]lowerCases=outputStream.toByteArray();

System.out.println(newString(lowerCases,0,lowerCases.length));

全部在内存中完成byte的转换

2、PrintStream:向目标打印

属于OutputStream的实现类,向目标(可能是文件、标准输出屏幕、输出流、网络等)打印各种样式,不过比一般的输出提供了更多的打印方式,可以打印各种数据类型和样式等

OutputStreamoutputStream=System.out;

outputStream.write("helloABC张三".getBytes());

outputStream.close();

列出当前操作系统的系统参数,输出到文件中

PrintStreamprintStream=newPrintStream("hello.txt");

System.getProperties().list(printStream);

printStream.close();

3、InputStreamReader、OutputStreamWriter, 计算机存储都是字节流的形式,而读取到内存中需要识别一个个的字符(人只能识别字符),有可能1个字节就代表一个字符(例如英文),也有可能多个字节才能转换成一个字符(例如中文),如果中间存在丢失或无法转换,则看到的就是一堆?

InputStreamReader:将输入的内容字节变成字符

OutputStreamWriter:将输出的内容从字符变成字节

4、合并流:SequenceInputStream

Filefile1=newFile("hello.txt");

Filefile2=newFile("test.txt");

InputStreaminputStream1=newFileInputStream(file1);

InputStreaminputStream2=newFileInputStream(file2);

SequenceInputStreamsequenceInputStream=newSequenceInputStream(inputStream1,

inputStream2);

BufferedInputStreambufferedInputStream=newBufferedInputStream(sequenceInputStream);

intc;

while((c=bufferedInputStream.read())!=-1){

System.out.print((char)c);

}

bufferedInputStream.close();

sequenceInputStream.close();

inputStream1.close();

inputStream2.close();

测试结果:helloworld

在实验中,从bufferedInputStream去取到两个文件大小相加的byte数组中,代码如下,转换出来有问题,有点奇怪,只读到了前一个流中的内容,后面一个流中的内容没读取进来。思考中...

Filefile1=newFile("hello.txt");

Filefile2=newFile("test.txt");

InputStreaminputStream1=newFileInputStream(file1);

InputStreaminputStream2=newFileInputStream(file2);

SequenceInputStreamsequenceInputStream=newSequenceInputStream(inputStream1,

inputStream2);

BufferedInputStreambufferedInputStream=newBufferedInputStream(sequenceInputStream);

intlength=(int)(file1.length()+file2.length());

byte[]b=newbyte[length];

bufferedInputStream.read(b,0,length);

System.out.println(newString(b,0,length));

bufferedInputStream.close();

sequenceInputStream.close();

inputStream1.close();

inputStream2.close();

测试结果如下:hello

5、Zip压缩与解压

压缩程序:

ZipOutputStreamzipOutputStream=newZipOutputStream(newFileOutputStream("hello.zip"));

zipOutputStream.setLevel(9);

ZipEntryzipEntry=newZipEntry("a.txt");

zipOutputStream.putNextEntry(zipEntry);

BufferedInputStreambufferedInputStream=newBufferedInputStream(newFileInputStream("test.txt"));

intcontent;

while((content=bufferedInputStream.read())!=-1){

zipOutputStream.write(content);

}

bufferedInputStream.close();

zipOutputStream.closeEntry();

zipOutputStream.flush();

zipOutputStream.close();

解压程序:

ZipInputStreamzipInputStream=newZipInputStream(newFileInputStream("hello.zip"));

ZipEntryzipEntry=null;

while((zipEntry=zipInputStream.getNextEntry())!=null){

BufferedOutputStreambufferedOutputStream=newBufferedOutputStream(

newFileOutputStream(zipEntry.getName()));

intcontent=0;

while((content=zipInputStream.read())!=-1){

bufferedOutputStream.write(content);

}

bufferedOutputStream.flush();

bufferedOutputStream.close();

}

zipInputStream.close();

6、zip压缩某目录下的所有文件及子文件

publicvoidzipDirectory(Filepathname,ZipOutputStreamzipOutputStream)throwsException{

if(!pathname.isDirectory()){

return;

}

File[]files=pathname.listFiles();

for(Filefile:files){

if(file.isDirectory()){

zipDirectory(file,zipOutputStream);

}else{

ZipEntryzipEntry=newZipEntry(pathname.getName()+File.separator

+file.getName());

zipOutputStream.putNextEntry(zipEntry);

BufferedInputStreambufferedInputStream=newBufferedInputStream(

newFileInputStream(file));

inti;

while((i=bufferedInputStream.read())!=-1){

zipOutputStream.write(i);

}

bufferedInputStream.close();

zipOutputStream.flush();

zipOutputStream.closeEntry();

}

}

}

问题:中文编码存在问题,建议选用import org.apache.tools.zip.ZipEntry;

import org.apache.tools.zip.ZipOutputStream,由于其存在方法out.setEncoding("gbk");//指定编码为gbk

6、ThreadLocal

finalThreadLocalthreadLocal=newThreadLocal();

threadLocal.set("main--");

Threadthread=newThread(){

@Override

publicvoidrun(){

threadLocal.set("thread--");

Thread.yield();

System.out.println(Thread.currentThread().getName()+":"+threadLocal.get());

}

};

thread.start();

Thread.yield();

System.out.println(Thread.currentThread().getName()+":"+threadLocal.get());

7、数组和List之间的转换

数组->List: Arrays.asList(a)

List->数组:list.toArray()

8、正则表达式

(1)^:在[]内表示取反,在外面表示开头

(2)group

Stringregex="[a-z]{3,5}";

Patternpattern=pile(regex,Pattern.CASE_INSENSITIVE);

Matchermatcher=pattern.matcher("Abc_defgh_aa_ABCD1");

while(matcher.find()){

System.out.print("位置[左闭右开区间):"+matcher.start()+"_"+matcher.end()+",匹配内容:");

System.out.println(matcher.group());

}

测试结果:

位置[左闭右开区间):0_3,匹配内容:Abc

位置[左闭右开区间):4_9,匹配内容:defgh

位置[左闭右开区间):13_17,匹配内容:ABCD

(3)邮件的正则表达式

[\\w[_.]]+@[\\w[_.]]+\\.[\\w]+

(4)"."点号在正则表达式中表示任何字符, 需要表示点号的时候必须转义\\.

(5)group的分组

分组是以正则表达式中的小括号'()'为标准的,当匹配成功后,group或group(0)表示匹配的整个字符串,group(1)代表正则中第一个小括号匹配到的内容,group(2)代表第二个小括号代表的内容,依次类推

(6)匹配require引入文件

"^[\\s]*#require[\\s]*\\(\"([\\w./]+)\"\\)[\\s]*$"含义为:以任意空白字符开头,在#require,再任意空白字符,再(",再任意字母、点号、斜线, 再"),最后任意个空白字符结尾

测试代码:

publicstaticvoidmain(String[]args){

FileInputStreamfileInputStream=null;

try{

fileInputStream=newFileInputStream(newFile(

"C:/DocumentsandSettings/***/MyDocuments/tmp/hello.js"));

}catch(FileNotFoundExceptione){

e.printStackTrace();

}

InputStreamReaderinputStreamReader=newInputStreamReader(fileInputStream,

Charset.defaultCharset());

BufferedReaderbufferedReader=newBufferedReader(inputStreamReader);

Stringline="";

try{

while((line=bufferedReader.readLine())!=null){

StringrequireFile=getRequireFile(line);

System.out.println(requireFile);

}

}catch(IOExceptione){

e.printStackTrace();

}finally{

try{

bufferedReader.close();

inputStreamReader.close();

fileInputStream.close();

}catch(IOExceptione){

e.printStackTrace();

}

}

}

privatestaticStringgetRequireFile(Stringline){

StringrequireFile="";

Patternpattern=Pattern

.compile("^[\\s]*#require[\\s]*\\(\"([\\w./]+)\"\\)[\\s]*$",Pattern.MULTILINE);

Matchermatcher=pattern.matcher(line);

while(matcher.find()){

requireFile=matcher.group(1);

}

returnrequireFile;

}

测试文件内容:

varparam;

#require("hello/world_util/alibaba123_utils.js")

#require("/abc/world_util/alibaba12666_utils.js")

测试结果

hello/world_util/alibaba123_utils.js

/abc/world_util/alibaba12666_utils.js

9、FileReader有待完备的地方,只能使用系统默认的字符集,而没有提供传递字符集的构造函数

FileReader继承了InputStreamReader,但并没有实现父类中带字符集参数的构造函数,所以

FileReader只能按系统默认的字符集来解码

10、阻塞队列:BlockingQueue

生产者中的 put() 操作会在没有空间可用时阻塞,而消费者的 take() 操作会在队列中没有任何东西时阻塞。

11、信号量:Semaphore, 允许规定数量的线程进入操作,释放之后其他进入执行

RunnablelimitedCall=newRunnable(){

finalRandomrand=newRandom();

finalSemaphoreavailable=newSemaphore(3);

intcount=0;

publicvoidrun(){

inttime=rand.nextInt(15);

intnum=count++;

try{

available.acquire();

System.out.println("Executing"+"long-runningactionfor"+time

+"seconds...#"+num);

Thread.sleep(time*1000);

System.out.println("Donewith#"+num+"!");

available.release();

}catch(InterruptedExceptionintEx){

intEx.printStackTrace();

}

}

};

for(inti=0;i<10;i++)

newThread(limitedCall).start();

12、死锁

publicclassDemo06{

publicstaticvoidmain(String[]args){

DeadLockdeadLock1=newDeadLock();

DeadLockdeadLock2=newDeadLock();

deadLock1.setFlag(true);

deadLock2.setFlag(false);

newThread(deadLock1).start();

newThread(deadLock2).start();

}

}

classDeadLockimplementsRunnable{

privatebooleanflag=false;

publicbooleanisFlag(){

returnflag;

}

publicvoidsetFlag(booleanflag){

this.flag=flag;

}

privatestaticObjectobject1=newObject();

privatestaticObjectobject2=newObject();

publicvoidrun(){

if(flag){

synchronized(object1){

System.out.println(Thread.currentThread().getName()+"getobject1.");

try{

Thread.sleep(1000);

}catch(InterruptedExceptione){

e.printStackTrace();

}

synchronized(object2){

System.out.println(Thread.currentThread().getName()+"getobject2.");

}

}

}else{

synchronized(object2){

System.out.println(Thread.currentThread().getName()+"getobject2.");

try{

Thread.sleep(1000);

}catch(InterruptedExceptione){

e.printStackTrace();

}

synchronized(object1){

System.out.println(Thread.currentThread().getName()+"getobject1.");

}

}

}

}

}

13、反射:通过classloader加载类,标准做法如下:

ClassLoadercl=Thread.currentThread().getContextClassLoader();

if(cl==null)cl=MyClass.class.getClassLoader();//fallback

Classclazz=cl.loadClass(name);

14、文件大小限制

错误做法:

publicintgetFileSize(Filef){

longl=f.length();

return(int)l;

}

正确做法如下:

不支持传递超过2GB的文件. 最好的做法是对长度进行检查, 溢出时抛出异常

publicintgetFileSize(Filef){

longl=f.length();

if(l>Integer.MAX_VALUE)thrownewIllegalStateException("intoverflow");

return(int)l;

}

15、线程sleep中断

try{

Thread.sleep(1000);

}catch(InterruptedExceptione){

Thread.currentThread().interrupt();

}

or

while(true){

if(Thread.currentThread().isInterrupted())break;

}

16、开发中常用术语解释

java的几种对象(PO,VO,DAO,BO,POJO)解释

一、PO:persistantobject持久对象,可以看成是与数据库中的表相映射的java对象。最简单的PO就是对应数据库中某个表中的一条记录,多个记录可以用PO的集合。PO中应该不包含任何对数据库的操作。

二、VO:valueobject值对象。通常用于业务层之间的数据传递,和PO一样也是仅仅包含数据而已。但应是抽象出的业务对象,可以和表对应,也可以不,这根据业务的需要.个人觉得同DTO(数据传输对象),在web上传递。

三、DAO:dataaccessobject数据访问对象,此对象用于访问数据库。通常和PO结合使用,DAO中包含了各种数据库的操作方法。通过它的方法,结合PO对数据库进行相关的操作。

四、BO:businessobject业务对象,封装业务逻辑的java对象,通过调用DAO方法,结合PO,VO进行业务操作。

五、POJO:plainordinaryjavaobject简单无规则java对象,我个人觉得它和其他不是一个层面上的东西,VO和PO应该都属于它。

17、多线售票系统:

classTicketSellerimplementsRunnable{

privateintticketCount=10;

@Override

publicvoidrun(){

while(ticketCount>0){

synchronized(this){

if(ticketCount>0){

try{

Thread.sleep(100);

}catch(InterruptedExceptione){

e.printStackTrace();

}

System.out.println(Thread.currentThread().getName()

+"sellticket:"+ticketCount--);

}

}

}

}

}

publicclassDemo01{

publicstaticvoidmain(String[]args){

TicketSellerticketSeller=newTicketSeller();

newThread(ticketSeller,"ThreadA").start();

newThread(ticketSeller,"ThreadB").start();

newThread(ticketSeller,"ThreadC").start();

newThread(ticketSeller,"ThreadD").start();

}

}

测试结果:

ThreadAsellticket:10

ThreadAsellticket:9

ThreadDsellticket:8

ThreadDsellticket:7

ThreadDsellticket:6

ThreadCsellticket:5

ThreadCsellticket:4

ThreadCsellticket:3

ThreadBsellticket:2

ThreadBsellticket:1

18、中断处理

classTicketSellerimplementsRunnable{

@Override

publicvoidrun(){

try{

System.out.println("线程启动");

Thread.sleep(10000);

}catch(InterruptedExceptione){

System.out.println("线程被中断");

//e.printStackTrace();

}

}

}

publicclassDemo01{

publicstaticvoidmain(String[]args)throwsInterruptedException{

TicketSellerticketSeller=newTicketSeller();

Threadthread=newThread(ticketSeller,"ThreadA");

thread.start();

System.out.println("====主线程执行===");

Thread.sleep(1000);

//thread.interrupt();

System.out.println("线程被中断否:"+thread.isInterrupted());

thread.interrupt();

System.out.println("线程被中断否:"+thread.isInterrupted());

System.out.println("线程被中断否2:"+thread.isInterrupted());

System.out.println("主线程是否被中断:"+Thread.interrupted());

System.out.println("====主线程结束===");

}

}

测试结果:

====主线程执行===

线程启动

线程被中断否:false

线程被中断否:true

线程被中断否2:true

主线程是否被中断:false

线程被中断

====主线程结束===

结论:

interrupt中断该线程,isInterrupted检查该线程是否被中断,interrupted检查当前线程是否被中断。

如果觉得《信号转化java_Java基础知识回顾-7》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。