package yuecheng.ch18; import java.io.*; public class BufferedInpuStreamDemo { /** * 从控制台输入内容,将输入的内容写到E盘下的某个文件夹的某个文件中 */ public static void main(String[] args) { //systemStreamMethodDemo(); try { systemToFileDemo(); } catch (Exception e) { e.printStackTrace(); } } /** * 把控制台写的数据输出到文本文件中 */ private static void systemToFileDemo() throws IOException { BufferedWriter bw= null; try { bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("E:/java.txt"))); } catch (FileNotFoundException e) { e.printStackTrace(); } BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String line=null; while((line=br.readLine())!=null){ if("over".equals(line)){ break; } try { bw.write(line); } catch (IOException e) { e.printStackTrace(); } try { bw.newLine(); } catch (IOException e) { e.printStackTrace(); } try { bw.flush(); } catch (IOException e) { e.printStackTrace(); } } try { br.close(); } catch (IOException e) { e.printStackTrace(); } try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } /** * 键盘的输入和输出 */ private static void systemStreamMethodDemo() throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out)); String line=null; while((line=br.readLine())!=null){ if("over".equals(line)){ break; } try { bw.write(line.toUpperCase()); } catch (IOException e) { e.printStackTrace(); } try { bw.newLine(); } catch (IOException e) { e.printStackTrace(); } try { bw.flush(); } catch (IOException e) { e.printStackTrace(); } } /** * 关闭流 关闭流原则:先开后关,后开先关。 */ try { br.close(); } catch (IOException e) { e.printStackTrace(); } try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } }
javaIO流练习2:从控制台输入内容,将输入的内容写到XX盘下的某个文件夹的某个文件中
最新推荐文章于 2024-04-23 22:38:15 发布