请教一个关于输入输出到txt文件的问题
做一个题目,要求是从input.txt文件中导入一个数据,并且计算从1到这个数据0-9各个数各出现多少次并且输出到output.txt文件,写了个程序,运行后不能正常的输出到output.txt文件,请假这个程序哪出问题了,谢谢拉
- Java code
package class1;public class Number { /** * @param args */ public static void main(String[] args) throws Exception { // TODO Auto-generated method stub int[] number = new int[10]; int in, n; java.io.File file1 = new java.io.File( "D:\\Homeworks\\eclipse work place\\SuanFa\\src\\class1\\input.txt"); java.util.Scanner input = new java.util.Scanner(file1); int page = input.nextInt(); for (int i = 1; i <= page; i++) { n = i; while (n >= 0) { in = n % 10; number[in]++; n = n / 10; } } java.io.File file2 = new java.io.File( "D:\\Homeworks\\eclipse work place\\SuanFa\\src\\class1\\output.txt"); if (file2.exists()) { System.out.println("File2 already exists"); System.exit(0); } java.io.PrintWriter output = new java.io.PrintWriter(file2); for (int j = 0; j <= 9; j++) { output.println("number " + j + " " + number[j]); } input.close(); output.close(); }}
[解决办法]
没看明白你的题是什么意思,我做了个简单的,你参照一下吧,希望对你有帮助。
FileReader rf = null;
FileWriter fw = null;
BufferedReader br = null;
try {
rf = new FileReader("d://a.txt");
fw = new FileWriter("d://b.txt");
br = new BufferedReader(rf);
char [] str = br.readLine().toCharArray();
Map map = new HashMap();
for(int i=0;i<str.length;i++){
if(map.containsKey(str[i]))
map.put(str[i],(Integer) map.get(str[i])+1);
else
map.put(str[i],1);
}
fw.write(map.toString());
System.out.println(map);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(IOException ce){
ce.printStackTrace();
}
finally{
try{
fw.flush();
fw.close();
br.close();
rf.close();
}catch(Exception ce){
ce.printStackTrace();
}
}