欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java中文件的读与写

程序员文章站 2022-04-08 21:38:16
...

 文件的读取

package javajava;

import java.io.FileInputStream;
import java.util.Scanner;

public class ReadFile {
    public static void main(String[] args) {
    	Scanner scan = new Scanner(System.in);
    	System.out.println("请输入文件地址:");
    	String str = scan.nextLine();
    	int count[] = new int[300];
    	int temp;
    	
    	try {   //必须在try里边
    		FileInputStream fin = new FileInputStream(str);//读取输入的文件
    		while((temp=fin.read())>0) {//如果读完的话   fin.read() =-1
    			count[temp]++;
    		}
    		fin.close();//别忘了close 文件
    		for(int i=32;i<=126;i++) {
    			if(count[i]>0) {
    				System.out.print((char)i);
    				System.out.println("-----"+i+"------"+count[i]);
    			}
    		}
    	}catch(Exception e) {
    		e.printStackTrace();
    	}
    }
}

文件的写:

package javajava;

import java.io.File;
import java.io.PrintStream;
import java.util.Scanner;

public class write {
	public static void main(String args[]) {
		Scanner scan = new Scanner(System.in);
		System.out.println("请输入一个数");
		int n = scan.nextInt();
		try {
			PrintStream fileout  = new PrintStream("a.txt");//必须在try 里边
			fileout.print(n);//直接写在文件里
			fileout.close();
		}catch(Exception e) {
			e.printStackTrace();
		}

	}
}

另一种写法

package javajava;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;

public class fileWrite {
	public void writeFile(File file,int [] prime) {
		try {
			FileOutputStream fos = new FileOutputStream(file);
			OutputStreamWriter osw = new OutputStreamWriter(fos,"UTF-8");
			BufferedWriter bw = new BufferedWriter(osw);
			for(int i=0;i<prime.length ;i++) {
				bw.write(prime[i]+" ");
				if(i%10==0)
					bw.write('\n');
			}
			bw.flush();
			bw.close();
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	public static void main(String[] args) {
		File file = new File("D:/txt11.txt");
		fileWrite fw = new fileWrite();
		int[] prime = {1,2,3,4,5};
		fw.writeFile(file,prime);
	}

}