java-打印流和Scanner使用用例,序列化反序列化用例
在桌面上新建一个Test.txt,使用打印流向文件中输出如下:
Hello 123
Hello 123
hello World
package com.PrinIO;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Test {
public static void main(String[] args) throws IOException, InterruptedException {
File file = new File("C:\\Users\\Administrator\\Desktop\\test.txt");
if(!file.exists()) {
file.createNewFile();
}
PrintWriter pw = new PrintWriter(file);
pw.write("Hello 123\r\n");
pw.write("Hello World\r\n");
pw.close(); //一个小坑,若不关闭该打印流,则下列Scanner将无法读入
Scanner scanner = new Scanner(new FileInputStream(file));
scanner.useDelimiter("\r\n");
while(scanner.hasNext()) {
System.out.println(scanner.next());
}
scanner.close();
}
}
自定义Person类,其中三个属性name,age,school.
age属性不作为序列化保存而其他两个属性使用序列化保存在本地文件TestSer.txt中
package com.PrinIO;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable; //注意添加包
@SuppressWarnings("serial")
class Person implements Serializable{
private String name;
private transient Integer age; //使用transient修饰将不会被序列化到文本当中
private String school;
public Person(String name, Integer age, String school) {
super();
this.name = name;
this.age = age;
this.school = school;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", school=" + school + "]";
}
}
public class Test2 {
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
Person person = new Person("张三", 20, "蓝翔技校");
File file = new File("C:\\Users\\Administrator\\Desktop\\person.txt");
if(!file.exists()) {
file.createNewFile();
}
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
oos.writeObject(person);
oos.close();
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
Object tmp = ois.readObject();
ois.close();
System.out.println(tmp);
}
}
一道算法:
输入一个5位数,判断它是不是回文数。即12321是回文数,个位与万位相同,十位与千位相同。
public class Test3 {
public static void main(String[] args) {
System.out.println("是否是回文数?"+isHuiWen(123454321));
}
// 输入一个5位数,判断它是不是回文数。即12321是回文数,个位与万位相同,十位与千位相同。 加强,输入任意长度的数:123454321
public static boolean isHuiWen(int num) {
int tmp=num, len=1;
while(tmp>=10) {
tmp/=10;
len++;
}
len = len/2;
for(int i=0;i<len;i++) {
int left = (num/(tenN(len*2-i)))%10;
int right = num/(tenN(i))%10;
System.out.println("left:"+left+",right"+right);
if(left!=right) {
return false;
}
}
return true;
}
public static int tenN(int n) {
int a = 1;
for(int i=0;i<n;i++) {
a*=10;
}
return a;
}
}