一、创建一个文件,文件内容afavcausivbhrghahnxkjaghvua,使用高效流读取文件中的内容存入到list集合中,统计字母出现的次数。
package com.home;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Test01 {
public static void main(String[] args) throws IOException {
List<Character> list = new ArrayList<>();
OutputStream os = new FileOutputStream("1.txt");
BufferedOutputStream bos = new BufferedOutputStream(os);
String s ="asfasvishb";
bos.write(s.getBytes());
bos.flush();
InputStream is = new FileInputStream("1.txt");
BufferedInputStream bis = new BufferedInputStream(is);
int length = -1;
while ((length=bis.read())!=-1){
list.add((char)length);
}
Map<Character,Integer> m = new HashMap<>();
for (int i =0;i<list.size();i++){
if (!m.containsKey(list.get(i))){
m.put(list.get(i),1);
}else {
m.put(list.get(i),m.get(list.get(i))+1);
}
}
System.out.println(m);
bis.close();
is.close();
bos.close();
os.close();
}
}
二、创建一个文件,内容:name=张三 age=12 pwd=234;读取文件,并打印张三 12 234。
package com.home;
import java.io.*;
public class Test02 {
public static void main(String[] args) throws IOException {
File f = new File("2.txt");
if (!f.exists()) {
f.createNewFile();
}
OutputStream os = new FileOutputStream("2.txt");
String s = "name=张三 age=18 pwd=234";
os.write(s.getBytes());
InputStream is = new FileInputStream("2.txt");
int length = -1;
byte[] b = new byte[1024];
String s1 = "";
while ((length = is.read(b)) != -1) {
s1 = new String(b, 0, length);
}
System.out.println(s1);
String[] arrays = s1.split(" ");
StringBuilder sb = new StringBuilder();
for (String r : arrays) {
sb.append(r.substring(r.indexOf("=") + 1) + " ");
}
System.out.println(sb);
is.close();
os.close();
}
}
三、使用代码创建文件1.txt,写入admin 12345,在读取出来写到另一个文件2.txt中
package com.home;
import java.io.*;
public class Test03 {
public static void main(String[] args) throws IOException {
File f = new File("d:\\admin\\dd");
if (!f.exists()) {
f.mkdirs();
}
File f1 = new File(f, "1.txt");
if (!f1.exists()) {
f1.createNewFile();
}
System.out.println("=================");
File f3 = new File("d:\\a\\b");
if (f3.exists()) {
f3.mkdirs();
}
File f4 = new File(f3, "2.txt");
if (!f4.createNewFile()) {
f4.createNewFile();
}
Writer w = new FileWriter(f1);
w.write("admin 12345");
w.flush();
Reader r = new FileReader(f1);
char[] c = new char[1024];
int length = -1;
String s = "";
while ((length = r.read(c)) != -1) {
s = new String(c, 0, length);
}
Writer w1 = new FileWriter(f4);
w1.write(s.split(" ")[0]);
w1.close();
r.close();
w.close();
}
}