Java读取文件内容和写入内容到文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lz527657138/article/details/78190536

Java读取文件内容方法和写入内容到文件方法

/**
	 * One.txt中的数据如下:
	 * 1
	 * 2
	 * 3
	 * 4
	 * 5
	 * -----------------
	 * 读操作方法
	 */
	@Test
	public void readFileToList2() {
		File file = new File("C:\\Users\\Desktop\\One.txt");
		System.out.println("文件绝对路径 :"+file.getAbsolutePath());
		List<String> listStr = new ArrayList<String>();
		BufferedReader br = null;
		String str = null;
		try {
			br = new BufferedReader(new FileReader(file));
			while ((str = br.readLine())!= null) {
				listStr.add(str);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println(listStr);
		writeListToFile(listStr);// 调用写操作方法
	}

	/**
	 * 实现写操作方法
	 */
	private void writeListToFile(List<String> listStr) {
		File file = new File("C:\\Users\\Desktop\\Azzan.txt");// 要写入的文件路径
		if (!file.exists()) {// 判断文件是否存在
			try {
				file.createNewFile();// 如果文件不存在创建文件
				System.out.println("文件"+file.getName()+"不存在已为您创建!");
			} catch (IOException e) {
				System.out.println("创建文件异常!");
				e.printStackTrace();
			}
		} else {
			System.out.println("文件"+file.getName()+"已存在!");
		}
		
		for (String str : listStr) {// 遍历listStr集合
			FileOutputStream fos = null;
			PrintStream ps = null;
			try {
				fos = new FileOutputStream(file,true);// 文件输出流	追加
				ps = new PrintStream(fos);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			String string  = str + "\r\n";// +换行
			ps.print(string); // 执行写操作
			ps.close();	// 关闭流
			
		}
		
		System.out.println("文件写入完毕!");
	}

猜你喜欢

转载自blog.csdn.net/lz527657138/article/details/78190536
今日推荐