在研究Android下断点上传文件时,遇到了一个java有意思的写法,break + 标签 积累下。
package com.zhcv.example.socket.util;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;
public class StreamTool {
public static void save(File file, byte[] data) throws Exception {
FileOutputStream outStream = new FileOutputStream(file);
outStream.write(data);
outStream.close();
}
public static String readLine(PushbackInputStream in) throws IOException {
char buf[] = new char[128];
int room = buf.length;
int offset = 0;
int c;
loop: while (true) {
switch (c = in.read()) {
case -1:
case '\n':
break loop;
case '\r':
int c2 = in.read();
if ((c2 != '\n') && (c2 != -1))
in.unread(c2);
break loop;
default:
if (--room < 0) {
char[] lineBuffer = buf;
buf = new char[offset + 128];
room = buf.length - offset - 1;
System.arraycopy(lineBuffer, 0, buf, 0, offset);
}
buf[offset++] = (char) c;
break;
}
}
if ((c == -1) && (offset == 0))
return null;
return String.copyValueOf(buf, 0, offset);
}
/**
* 读取流
*
* @param inStream
* @return 字节数组
* @throws Exception
*/
public static byte[] readStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while ((len = inStream.read(buffer)) != -1) {
outSteam.write(buffer, 0, len);
}
outSteam.close();
inStream.close();
return outSteam.toByteArray();
}
}
在readLine函数中while(true)死循环边有一个标签loop,在switch语句case中有break loop语句。原来在C语言中只见过goto+标签的语句。查找相关资料才知道break + 标签语句是结束指定语句所控制的语句。
下面有两个例子,大家可以试验:
public class H {
public static void main(String[] args) {
{
back: for (int i = 0; i < 10; i++) {
if (i == 9) {
System.out.println("break");
break back;
}
}
System.out.println("test");
}
}
}
打印结果为
break
test
在看一个
public class H {
public static void main(String[] args) {
back:{
for (int i = 0; i < 10; i++) {
if (i == 9) {
System.out.println("break");
break back;
}
}
System.out.println("test");
}
}
}
打印结果为:
break
带标签的break是退出标签所指的地方所管的“领空”,而不会从标签所指的地方重新开始执行,因此上诉代码都不会从所指的for开始无限死循环