String构造方法举例
//用数组构造一个字符串
public class StringTest {
public static void main(String[] args) {
char[] c = {'s', 'u', 'n', ' ', 'j', 'a', 'v', 'a'};
String s1 = new String(c);
//从第4个下标处开始截取字符串,截取4个字符
String s2 = new String(c, 4, 4);
System.out.println(s1);
System.out.println(s2);
}
}
String类常用方法
//valueOf方法和split方法
public class StringTest1 {
public static void main(String[] args) {
int j = 1234567;
String str = String.valueOf(j);
System.out.println("j是"+str.length()+"位数");
String s = "my,love";
String[] split = s.split(",");
for(int i = 0; i < split.length; i++) {
System.out.println(split[i]);
}
}
}
String和StringBuffer的区别
//String类和StringBuffer类的区别
public class StringTest2 {
public static void main(String[] args) {
//String是不可变的字符序列
String s1 = "hello";
String s2 = " world";
s1 += s2;
System.out.println(s1);
//StringBuffer是可变的字符序列
StringBuffer s3 = new StringBuffer();
s3.append("hello");
s3.append(" world");
System.out.println(s3);
}
}
以上程序的内存情况:
如果是StringBuffer就可以直接在s1后面分配内存并将s2复制过来,实现字符串的连接
StringBuffer常用的方法
常用包装类
//包装类的应用
public class ArrayPaser {
public static void main(String[] args) {
double[][] arr;
String s = "1, 2; 3, 4, 5; 6, 7, 8";
String[] sFirst = s.split(";");
arr = new double[sFirst.length][];
for(int i = 0; i < sFirst.length; i++) {
String[] sSecond = sFirst[i].split(",");
arr[i] = new double[sSecond.length];
for(int j = 0; j < sSecond.length; j++) {
arr[i][j] = Double.parseDouble(sSecond[j]);
}
}
for(int i = 0; i < arr.length; i++) {
for(int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
File类
//File类
public class FileTest {
public static void main(String[] args) {
//分隔符,windows和linux系统下通用
String separator = File.separator;
//文件名
String fileName = "myfile.txt";
//路径
String directory = "F:"+separator+"DB"+separator+"mydir";
File f = new File(directory, fileName);
if(f.exists()) {
System.out.println("文件名:"+f.getAbsolutePath());
System.out.println("文件大小:"+f.length());
}else{
try {
//创建路径
f.getParentFile().mkdirs();
//创建文件
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//递归列出指定目录下的所有子目录和子文件
public class FileList {
public static void main(String[] args) {
File f = new File("F:/DB/mydir");
System.out.println(f.getName());
tree(f, 1);
}
private static void tree(File f, int level) {
String preStr = "";
for(int i = 0; i < level; i++) {
preStr += " ";
}
//拿到所有的孩子目录和文件
File[] childs = f.listFiles();
for(int i = 0; i < childs.length; i++) {
System.out.println(preStr + childs[i].getName());
//如果是目录,进行递归
if(childs[i].isDirectory()) {
//递归
tree(childs[i], level + 1);
}
}
}
}
枚举类型
//枚举
public class EnumTest {
public enum MyColor{
red, green, blue
}
public static void main(String[] args) {
MyColor m = MyColor.red;
switch(m) {
case red:
System.out.println("red"); //red
break;
case green:
System.out.println("green");
break;
default:
System.out.println("default");
}
System.out.println(m); //red
}
}