IO practice question collection (IO realizes image encryption, copy files according to file path, enter data, reverse text, obtain the number of bytes in the text, make trial version software)

1. Picture encryption

The idea is that we can encrypt the picture as long as we XOR the previous number when inputting bytes

public static void main(String[] args) throws IOException {
    
    
		BufferedInputStream bis=new BufferedInputStream(new FileInputStream("6.jpg"));
		BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("copy.jpg"));
		int b;
		while ((b=bis.read())!=-1) {
    
    
			bos.write(b^123);
		}
		bos.close();
		bis.close();
	}

The effect is as follows: Insert picture description here
if we need to decrypt, we only need to change the input and output file name and it will be ok. which is

BufferedInputStream bis=new 
BufferedInputStream(new FileInputStream("copy.jpg"));
BufferedOutputStream bos=new 
BufferedOutputStream(new FileOutputStream("copy2.jpg"));

2. Copy files according to the file Road King

Requirements: Enter the path of the file in the console and copy the file to the current project.
Analysis:

  1. Create keyboard entry objects

  2. The definition method judges the path entered by the keyboard, and returns if it is a file.

  3. Accept the file in the main method

  4. Read and write the file

Steps: Define a method to get the file path entered by the keyboard, and encapsulate it into a File object to return

  1. Return value type File
  2. Parameter list none
public class Test2 {
    
    

public static void main(String[] args) throws IOException {
    
    
			File file =getFile();
BufferedInputStream bufferedInputStream =
new BufferedInputStream(new FileInputStream(file));
BufferedOutputStream bufferedOutputStream =
new BufferedOutputStream(newFileOutputStream(file.getName()));
			
	    int b;
while ((b=bufferedInputStream.read())!=-1) {
    
    
				 bufferedOutputStream.write(b);
			}
			bufferedInputStream.close();
			bufferedInputStream.close();
	}
	//定义一个方法获取文件路径,并封装成File对象返回
	//返回类型File
	//参数列表无
	public static File getFile() {
    
    
		Scanner scanner =new Scanner(System.in);
		System.out.println("请输入一个文件的路径");
		while(true) {
    
    
		String line =scanner.nextLine();
		File file =new File(line);
		if (!file.exists()) {
    
    
			System.out.print("您录入的文件路径不存在,请重新录入:");
		}else if(file.isDirectory()){
    
    
			System.out.println("您录入的是文件夹路径,请重新录入:");
		}else {
    
    
			return file;
		}
	}
		}
}

At this time, we enter the location of a file in the console.
For example: Insert picture description here
At this time, we will have an extra picture under the project.
Insert picture description here

3. Copy input data to file

Requirement: Copy the data entered by the keyboard to the text.txt file under the current project, and exit when the data entered by the keyboard encounters quit.
analysis:

  1. Create keyboard entry objects
  2. Create output stream object and associate text.txt file
  3. Define an infinite loop
  4. Encountered quit to exit the loop
  5. If it is not quit, continue writing
public class Test3 {
    
    

	public static void main(String[] args) throws IOException{
    
    
		// TODO Auto-generated method stub
		Scanner scanner =new Scanner(System.in);
		FileOutputStream fileOutputStream =new FileOutputStream("text.txt");
		System.out.print("请输入内容");
		while (true) {
    
    
			String line=scanner.nextLine();
			if (line.equals("quite")) {
    
    
				break;
			}
			else {
    
    
				fileOutputStream.write(line.getBytes());			//字符串写出必须转换成字节数组
				fileOutputStream.write("\r\n".getBytes());
			}
		}
		fileOutputStream.close();
		
	}

}

Fourth, reverse the text

Requirements: Reverse the text on a text document, swap the first line with the penultimate line, and swap the second line with the penultimate line.
Analysis:
Step 1: Create input and output stream objects
Step 2: Create collection objects, temporarily store the data, and write backwards through traversal
Step 3: Store the read data in the collection
Step 4: Back Traverse the collection and write the data to the file
Step 5: Close the stream

public class Test4 {
    
    
	public static void main(String[] args) throws IOException {
    
    
		// TODO Auto-generated method stub
		//1.创建输入输出流对象
BufferedReader bufferedReader =new BufferedReader(new FileReader("zzz.txt"));
BufferedWriter bufferedWriter =new BufferedWriter(new FileWriter("rezzz.txt"));
		//2.创建集合对象
		List <String> list =new ArrayList<String>();
		String line;
		while ((line=bufferedReader.readLine())!=null) {
    
    
			list.add(line);
		}
		for (int i = list.size()-1; i >=0; i--) {
    
    
			bufferedWriter.write(list.get(i));
			bufferedWriter.newLine();
		}
		bufferedReader.close();
		bufferedWriter.close();
	}

}

5. Get the number of occurrences of characters (each character, each word) in the text

Requirements: Get the number of occurrences of each character in a text, and write the result on times.txt
Analysis:

  1. Create a buffered input stream object
  2. Create a two-column collection object TreeMap
  3. Store the read characters in a two-column set, and make a judgment when storing. If this key is not included, then the key and 1 will be stored. If the key is included, the key and value will be stored by adding 1
  4. Close the input stream and create an output stream object
  5. Traverse the contents of the collection and write the contents of the collection to times.txt,
  6. Close output stream
public class Test2 {
    
    

	public static void main(String[] args) throws IOException {
    
    
		// TODO Auto-generated method stub
		//1.创建带缓冲的输入流对象
		BufferedReader bufferedReader =new BufferedReader(new FileReader("zzz.txt"));
		//2.创建双列集合对象TreeMap
		TreeMap<Character,Integer> treeMap =new TreeMap<Character,Integer> ();
		int ch;
		while ((ch=bufferedReader.read())!=-1) {
    
    
			char c=(char)ch;		//强制转换
			treeMap.put(c, !treeMap.containsKey(c)?1:treeMap.get(c)+1);
		}
		//4.关闭输入流
		bufferedReader.close();
		//5.创建输出流对象
		BufferedWriter bufferedWriter =new BufferedWriter(new FileWriter("times.txt"));
		//6.遍历集合将集合中的内容写到times.txt中
		for (Character key : treeMap.keySet()) {
    
    
			switch (key) {
    
    
			case '\t':
				bufferedWriter.write("\\t"+"==="+treeMap.get(key));
				break;
			case '\n':
				bufferedWriter.write("\\n"+"==="+treeMap.get(key));
			default:
				break;
			}
			bufferedWriter.write(key+"==="+treeMap.get(key));
			bufferedWriter.newLine();
		}
		//7.关闭输出流
		bufferedWriter.close();
	}

}

The effect is as follows:
Insert picture description here

Six, make a trial version of the software

Requirements: * When we download a trial version of the software, when we have not purchased the original version, we will remind us how many times we have the opportunity to use the learned IO stream knowledge every time we execute it, simulate the trial version of the software, try 10 opportunities, and execute once Just a reminder once you have several opportunities, if the number of times is up, please buy the original.
Analysis:
1. Create a buffered input stream object because the readLine method is used. Can guarantee the originality of the data
2. Convert the read string to an int number
3. Judge the int number. If it is greater than 0, write it back. If it is not greater than 0, it will prompt to buy a genuine copy
. 4. In the if judgment, print the result of--and write the result to the file through the output stream

public class Test3 {
    
    
	public static void main(String[] args) throws IOException {
    
    
		//1.创建带缓冲的输入流对象,因为要使用readLine方法。可以保证数据的原样性
		BufferedReader  bufferedReader =new BufferedReader(new FileReader("config.txt"));
		//2.将读到的字符串转换为int数
		String line =bufferedReader.readLine();
		int times = Integer.parseInt(line);
		if (times > 0) {
    
    
			System.out.println("您还有"+times--+"次机会");
			FileWriter fileWriter =new FileWriter("config.txt");
			fileWriter.write(times+"");
			fileWriter.close();
		}else {
    
    
			System.out.println("您的试用次数已到,请购买正版。");
		}
		bufferedReader.close();
	}
}

If we write 10 times in config.txt, every time we run it, the number of times will decrease.

Seven, memory output stream

Requirement: Define a file input stream, call the read(byte[] b) method, and print the content in the a.txt file (the byte array size is limited to 5)
Analysis:
1. read(byte[] b) is a byte The method of input stream, create FileInputStream, associate a.txt
2. Create a byte array with a length of 5
3. Convert all the data in the memory output stream into a string for printing
4. Close the input stream

     	FileInputStream fis =new FileInputStream("a.txt");
		
		ByteArrayOutputStream byteArrayOutputStream =new ByteArrayOutputStream();
		int len;
		//3.创建字节数组,长度为5
		byte[] arr=new byte[5];
		while ((len=fis.read(arr))!=-1) {
    
    
			byteArrayOutputStream.write(arr,0,len);
			//如果没有字符内存数组,
			//System.out.println(new String(arr,0,len));
		}
		//将内存输出流的数据全部转换为字符串打印
		System.out.println(byteArrayOutputStream);	//即使没有调用,底层也会默认帮我们调用toString()方法
		fis.close();

Guess you like

Origin blog.csdn.net/Mr_GYF/article/details/108818435