zoukankan      html  css  js  c++  java
  • 04747_Java语言程序设计(一)_第9章_输入和输出流

    例9.1一个文件复制应用程序,将某个文件的内容全部复制到另一个文件。

    import java.io.*;
    
    public class Example9_1 {
    	public static void main(String arg[]) {
    		File inputFile = new File("file1.txt");
    		File outputFile = new File("file2.txt");
    		int ch;
    		try {
    			FileReader in = new FileReader(inputFile);
    			FileWriter out = new FileWriter(outputFile);
    			System.out.print("文件复制程序开始工作:");
    			while ((ch = in.read()) != -1) {
    				out.write(ch);
    			}
    			in.close();
    			out.close();
    			System.out.print("文件复制程序工作结束:");
    		} catch (FileNotFoundException e1) {
    			System.out.print("文件没有找到!" + e1);
    		} catch (IOException e2) {
    			System.out.print("File read Error:" + e2);
    		}
    	}
    }
    

    例9.2说明BufferedReader类的用法的应用程序。

    import java.io.*;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    
    class MyWindow extends JFrame implements ActionListener {
    	JTextArea text;
    	BufferedReader in;
    	JButton button;
    	FileReader file;
    
    	MyWindow() {
    		super("缓冲式流的读取");
    		Container con = this.getContentPane();// 获得内容面板
    		con.setSize(100, 400);
    		con.setLayout(new BorderLayout());
    		button.addActionListener(this);
    		text = new JTextArea(20, 30);
    		text.setBackground(Color.cyan);
    		JScrollPane jsp = new JScrollPane(text);
    		con.add(jsp, BorderLayout.CENTER);
    		con.add(button, "South");
    		this.setVisible(true);
    		this.pack();
    		try {
    			File f = new File("Example9_3.java");// 指定文件
    			file = new FileReader(f);// 创建FileReader对象
    			in = new BufferedReader(file);// 接到BufferedReader类对象上
    		} catch (FileNotFoundException e1) {
    			text.setText("文件没有找到");
    			button.removeActionListener(this);
    		}
    	}
    
    	public void actionPerformed(ActionEvent e) {
    		String s;
    		if (e.getSource() == button) {
    			try {
    				while ((s = in.readLine()) != null)// 按行输入
    				{
    					text.append(s + '
    ');// 从文件读出的内容在文本区中输出
    				}
    			} catch (IOException exp) {
    			}
    		}
    	}
    }
    
    public class Example9_2 {
    	public static void main(String args[]) {
    		MyWindow myWin = new MyWindow();
    	}
    }
    

    例9.3说明BufferedWriter类用法的应用程序。

    import java.util.*;
    import java.io.*;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    
    class MyWindow extends JFrame implements ActionListener {
    	JTextArea text;
    	JButton button;
    	FileWriter writefile;
    	BufferedWriter out;
    
    	MyWindow() {
    		super("缓冲式样流的输出");
    		Container con = this.getContentPane();// 获得内容面板
    		text = new JTextArea(20, 30);
    		text.setBackground(Color.cyan);
    		button = new JButton("写文件");
    		button.addActionListener(this);
    		con.setLayout(new BorderLayout());
    		con.setSize(40, 40);
    		con.setVisible(true);
    		con.add(text, "Center");
    		con.add(button, "South");
    		try {
    			writefile = new FileWriter("line.txt");
    			out = new BufferedWriter(writefile);
    		} catch (IOException e) {
    		}
    	}
    
    	public void actionPerformed(ActionEvent e) {
    		String s;
    		if (e.getSource() == button) {// 将文本区内容采用缓冲式输出到文件
    			try {
    				out.write(text.getText(), 0, (text.getText()).length());
    				out.flush();
    				text.setText(null);
    				System.exit(0);
    			} catch (IOException exp) {
    				text.setText("文件写出错!
    ");
    				System.exit(-1);
    			}
    		}
    	}
    }
    
    public class Example9_3 {
    	public static void main(String args[]) {
    		MyWindow myWin = new MyWindow();
    		myWin.pack();
    	}
    }
    

    例9.4一个文件随机读写的应用程序。

    import java.io.*;
    
    public class Example9_4 {
    	public static void main(String args[]) {
    		RandomAccessFile inOut = null;
    		long data[] = { 151, 278, 235, 206, -170, 32, 43, 21, 83, 47 };
    		try {
    			inOut = new RandomAccessFile("longData.dat", "rw");
    			for (int i = 0; i < data.length; i++) {
    				inOut.writeLong(data[i]);
    			}
    			for (int i = data.length - 1; i >= 0; i--) {
    				inOut.seek(i * 8);// long型数据占8个字节,第i个整数自i*8字节开始
    				System.out.print(" " + inOut.readLong() + ((i == 0) ? "
    " : ","));
    			}
    			inOut.close();
    		} catch (FileNotFoundException e1) {
    			System.out.println("文件找不到!" + e1);
    		} catch (IOException e2) {
    			System.out.println("文件读写错!" + e2);
    		}
    	}
    }
    

    例9.5应用程序逐行读取自己的源代码显示。

    import java.io.*;
    
    public class Example9_5 {
    	public static void main(String args[]) {
    		try {
    			RandomAccessFile file = new RandomAccessFile("Example9_5.java", "rw");
    			long fileCurPos = 0;
    			long fileLength = file.length();
    			while (fileCurPos < fileLength) {
    				String s = file.readLine();
    				System.out.println(s);
    				fileCurPos = file.getFilePointer();
    			}
    			file.close();
    		} catch (FileNotFoundException e1) {
    			System.out.println("文件找不到!" + e1);
    		} catch (IOException e2) {
    			System.out.println("文件读写错!" + e2);
    		}
    	}
    }
    

    例9.6应用程序利用文件对话框确定数据文件。

    import java.awt.*;
    import javax.swing.*;
    import java.io.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.filechooser.*;
    import javax.swing.filechooser.FileFilter;
    
    public class Example9_6 {
    	public static void main(String args[]) {
    		FrameFileDialog f = new FrameFileDialog();
    	}
    }
    
    class FrameFileDialog extends JFrame implements ActionListener {
    	JFileChooser filedialog = null;
    	JLabel label = new JLabel("", JLabel.CENTER);
    	JButton b1, b2;
    	JTextArea text;
    
    	FrameFileDialog() {
    		super("带文件对话框的窗口");
    		Container con = this.getContentPane();
    		con.setLayout(new BorderLayout());
    		con.setSize(40, 50);
    		JPanel p = new JPanel();
    		b1 = new JButton("打开文件");
    		b2 = new JButton("保存文件");
    		b1.addActionListener(this);
    		b2.addActionListener(this);
    		p.add(b1);
    		p.add(b2);
    		text = new JTextArea(20, 30);
    		JScrollPane jsp = new JScrollPane(text);
    		filedialog = new JFileChooser("D:\workspace");
    		/* 建立一个JFileChooser对象,并指定目录为默认文件对话框路径 */
    		filedialog.setControlButtonsAreShown(true);// 显示打开和撤销按钮
    		filedialog.addChoosableFileFilter(new MyFileFilter("txt"));
    		filedialog.addChoosableFileFilter(new MyFileFilter("java"));
    		text.setBackground(Color.cyan);
    		con.add(jsp, BorderLayout.CENTER);
    		con.add(label, BorderLayout.NORTH);
    		con.add(p, BorderLayout.SOUTH);
    		this.setVisible(true);
    		this.pack();
    	}
    
    	public void actionPerformed(ActionEvent e) {
    		File file = null;
    		int result;
    		if (e.getSource() == b1)// 打开文件
    		{
    			filedialog.setDialogTitle("打开文件");
    			result = filedialog.showOpenDialog(this);
    			text.setText("");
    			if (result == JFileChooser.APPROVE_OPTION) {
    				file = filedialog.getSelectedFile();
    				label.setText("你选择打开的文件名称是:" + file.getName());
    			} else if (result == JFileChooser.CANCEL_OPTION) {
    				label.setText("你没有选择任何文件");
    			}
    			FileInputStream fileStream = null;
    			if (file != null) {
    				try {
    					fileStream = new FileInputStream(file);
    				} catch (FileNotFoundException nfe) {
    					label.setText("文件没有找到");
    					return;
    				}
    				int readByte;
    				try {
    					while ((readByte = fileStream.read()) != -1) {
    						text.append(String.valueOf((char) readByte));
    					}
    					fileStream.close();
    				} catch (IOException ie) {
    					label.setText("读取文件出错");
    				}
    			}
    		} else if (e.getSource() == b2)// 保存文件
    		{
    			filedialog.setDialogTitle("保存文件");
    			result = filedialog.showSaveDialog(this);
    			file = null;
    			String fileName;
    			if (result == JFileChooser.APPROVE_OPTION) {
    				file = filedialog.getSelectedFile();
    				label.setText("你选择保存的文件名称是:" + file.getName());
    			} else if (result == JFileChooser.CANCEL_OPTION) {
    				label.setText("你没有选择任何文件");
    			}
    			FileOutputStream fileStream = null;
    			if (file != null) {
    				try {
    					fileStream = new FileOutputStream(file);
    				} catch (FileNotFoundException nfe) {
    					label.setText("文件没有找到");
    					return;
    				}
    				String content = text.getText();
    				try {
    					fileStream.write(content.getBytes());
    					fileStream.close();
    				} catch (IOException ie) {
    					label.setText("写文件出错");
    				}
    			}
    		}
    	}
    }
    
    class MyFileFilter extends FileFilter {
    	String ext;
    
    	MyFileFilter(String t) {
    		ext = t;
    	}
    
    	public boolean accept(File file) {
    		if (file.isDirectory()) {
    			return true;
    		}
    		String fn = file.getName();
    		int index = fn.lastIndexOf(',');
    		if (index > 0 && index < fn.length() - 1) {
    			String extension = fn.substring(index + 1).toLowerCase();
    			if (extension.equals(ext)) {
    				return true;
    			}
    		}
    		return false;
    	}
    
    	public String getDescription() {
    		if (ext.equals("java")) {
    			return "JAVA Source File(*.java)";
    		}
    		if (ext.equals("txt")) {
    			return "TXT File(*.txt)";
    		}
    		return "";
    	}
    }
    
  • 相关阅读:
    shutdown(0)和shutdown(1)
    MAC Pro 同时安装 Python2 和 Python3
    Linux常用命令大全(非常全!!!)
    ReentrantLock和synchronized的区别
    ReentrantLock和synchronized的区别
    ReentrantLock和synchronized的区别
    ReentrantLock和synchronized的区别
    Java反射与注解
    Java反射与注解
    Java反射与注解
  • 原文地址:https://www.cnblogs.com/denggelin/p/6242244.html
Copyright © 2011-2022 走看看