资源描述
一:JAVA读写
读文件:
FileInputStream
通过打开一个到实际文件的连接来创建一个 FileInputStream,该文件通过文件系统中的路径名
name 指定。创建一个新 FileDescriptor 对象来表示此文件连接。
InputStreamReader
InputStreamReader 是字节流通向字符流的桥梁:它使用指定的 charset 读取字节并将其解码为字
符。它使用的字符集可以由名称指定或显式给定,否则可能接受平台默认的字符集。
BufferedReader
从字符输入流中读取文本,缓冲各个字符,从而提供字符、数组和行的高效读取。 可以指定缓冲区
的大小,或者可使用默认的大小。大多数情况下,默认值就足够大了。
StringBuffer
线程安全的可变字符序列。一个类似于 String 的字符串缓冲区,但不能修改。虽然在任意时间点上
它都包含某种特定的字符序列,但通过某些方法调用可以改变该序列的长度和内容。
public static void main(String[] args) {
//读取文件内容
File a = new File("C:/add2.txt");
if(a.exists()){
FileInputStream fi = new FileInputStream(a);
InputStreamReader isr = new InputStreamReader(fi, "GBk");
BufferedReader bfin = new BufferedReader(isr);
String rLine = "";
while((rLine = bfin.readLine())!=null){
System.out.println(rLine);
}
}
}
写文件:
在 java写文件中,通常会使用FileOutputStream和FileWriter,FileWriter只能写文本文件。 FileOutputStream也经常结合BufferedOutputStream。因为实际应用中写文本文件的情况占了大多数。所以下面测试用不同的方式生成一个相同行数、大小相同的文件的三种不同方式。
import java.io.File;
import java.io.FileOutputStream;
import java.io.*;
public class FileTest {
public FileTest() {
}
public static void main(String[] args) {
FileOutputStream out = null;
FileOutputStream outSTr = null;
BufferedOutputStream Buff=null;
FileWriter fw = null;
int count=1000;//写文件行数
try {
out = new FileOutputStream(new File("C:/add.txt"));
long begin = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
out.write("测试java 文件操作\r\n".getBytes());
}
out.close();
long end = System.currentTimeMillis();
System.out.println("FileOutputStream执行耗时:" + (end - begin) + " 豪秒");
outSTr = new FileOutputStream(new File("C:/add0.txt"));
Buff=new BufferedOutputStream(outSTr);
long begin0 = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
Buff.write("测试java 文件操作\r\n".getBytes());
}
Buff.flush();
Buff.close();
long end0 = System.currentTimeMillis();
System.out.println("BufferedOutputStream执行耗时:" + (end0 - begin0) + " 豪秒");
fw = new FileWriter("C:/add2.txt");
long begin3 = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
fw.write("测试java 文件操作\r\n");
}
fw.close();
long end3 = System.currentTimeMillis();
System.out.println("FileWriter执行耗时:" + (end3 - begin3) + " 豪秒");
} catch (Exception e) {
e.printStackTrace();
}
finally {
try {
fw.close();
Buff.close();
outSTr.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
以下结果经过多次执行,取常出现的数据,由于只是简单比较,不做详细统计。
1.当count=1000的,即写文件1000行的时候,写出的文件大小为18.5KB:
FileOutputStream执行耗时:46 豪秒
BufferedOutputStream执行耗时:31 豪秒
FileWriter执行耗时:15 豪秒
2.当count=10000的,即写文件10000行的时候,写出的文件大小为185KB:
FileOutputStream执行耗时:188 豪秒
BufferedOutputStream执行耗时:32 豪秒
FileWriter执行耗时:16 豪秒
3.当count=100000的,即写文件100000行的时候,写出的文件大小为1856KB:
FileOutputStream执行耗时:1266 豪秒
BufferedOutputStream执行耗时:125 豪秒
FileWriter执行耗时:93 豪秒
4.当count=1000000的,即写文件1000000行的时候,写出的文件大小为18555KB:
FileOutputStream执行耗时:12063 豪秒
BufferedOutputStream执行耗时:1484 豪秒
FileWriter执行耗时:969 豪秒
由以上数据可以看到,如果不用缓冲流BufferedOutputStream,FileOutputStream写文件的鲁棒性是很不好的。当写 1000000行的文件的时候,FileOutputStream比FileWriter要慢11094毫秒(11 秒),BufferedOutputStream比FileWriter慢515毫秒。
不要小看这几秒的时间。当操作的数据量很大的时候,这点性能的差距就会很大了。在通用数据迁移工具导出数据库2千万条记录生成sql脚本文件的时候,性能性能相差10分钟以上。
二:JAVA文件追加内容
package com.thread.test;
import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;
public class AppendToFile {
public static void appendMethodA(String fileName,
String content){
try {
// 打开一个随机访问文件流,按读写方式
RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
// 文件长度,字节数
long fileLength = randomFile.length();
//将写文件指针移到文件尾。
randomFile.seek(fileLength);
randomFile.writeBytes(content);
randomFile.close();
} catch (IOException e){
e.printStackTrace();
}
}
public static void appendMethodB(String fileName, String content){
try {
//打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件
FileWriter writer = new FileWriter(fileName, true);
writer.write(content);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String fileName = "D:/t2.txt";
String content = "new append!";
//按方法A追加文件
AppendToFile.appendMethodA(fileName, content);
AppendToFile.appendMethodA(fileName, "append end. n");
//显示文件内容
ReadFromFile.readFileByLines(fileName);
//按方法B追加文件
AppendToFile.appendMethodB(fileName, content);
AppendToFile.appendMethodB(fileName, "append end. n");
//显示文件内容
ReadFromFile.readFileByLines(fileName);
}
}java.lang.String.contains() 方法返回true,当且仅当此字符串包含指定的char值序列
1. 输入:
格式为:Scanner cin = new Scanner (new BufferedInputStream(System.in));
//加Buffer可能会快一些
Scanner cin = new Scanner (System.in);
例程:
iimport java.util.Scanner;
import java.io.BufferedInputStream;
import java.math.BigInteger;
public class Main
{
public static void main(String[] args)
{
Scanner cin = new Scanner (new BufferedInputStream(System.in));
int a;
double b;
BigInteger c;
String st;
a = cin.nextInt();
b = cin.nextDouble();
c = cin.nextBigInteger();
st = cin.nextLine(); // 每种类型都有相应的输入函数.
}
}
读一个整数:int n = cin.nextInt(); 相当于 scanf("%d", &n); 或 cin >> n;
读一个字符串:String s = cin.next(); 相当于 scanf("%s", s); 或 cin >> s;
读一个浮点数:double t = cin.nextDouble(); 相当于 scanf("%lf", &t); 或 cin >> t;
读一整行: String s = cin.nextLine(); 相当于 gets(s); 或 cin.getline(...);
判断是否有下一个输入可以用 cin.hasNext() 或 cin.hasNextInt() 或 cin.hasNextDouble()
2. 输出
System.out.print(); // cout << …;
System.out.println(); // cout << … << endl;
System.out.printf(); // 与C中的printf用法类似.
例程:
import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner cin = new Scanner (new BufferedInputStream(System.in));
int a; double b;
a = 12345;
b = 1.234567;
System.out.println(a + " " + b);
// 输出b为字宽为10,右对齐,保留小数点后5位,四舍五入.
System.out.printf("%d %10.5f\n", a, b);
}
}
规格化的输出:
函数:
// 这里0指一位数字,#指除0以外的数字(如果是0,则不显示),四舍五入.
DecimalFormat fd = new DecimalFormat("#.00#");
DecimalFormat gd = new DecimalFormat("0.000");
System.out.println("x =" + fd.format(x));
System.out.println("x =" + gd.format(x));
对于输出浮点数保留几位小数的问题,可以使用DecimalFormat类,
import java.text.*;
DecimalFormat f = new DecimalFormat("#.00#");
DecimalFormat g = new DecimalFormat("0.000");
double a = 123.45678, b = 0.12;
System.out.println(f.format(a));
System.out.println(f.format(b));
System.out.println(g.format(b));
3. 字符串处理
java中字符串String是不可以修改的,要修改只能转换为字符数组.
String 类用来存储字符串,可以用charAt方法来取出其中某一字节,计数从0开始:
String a = "Hello"; // a.charAt(1) = 'e'
用substring方法可得到子串,如上例
System.out.println(a.substring(0, 4)) // output "Hell"
注意第2个参数位置上的字符不包括进来。这样做使得 s.substring(a, b) 总是有 b-a个字符。
字符串连接可以直接用 + 号,如
String a = "Hello";
String b = "world";
System.out.println(a + ", " + b + "!"); // output "Hello, world!"
如想直接将字符串中的某字节改变,可以使用另外的StringBuffer类。
例程:
import java.io.*;
import java.util.*;
public class Main
{
public static void main(String[] args)
{
int i;
Scanner cin = new Scanner (new BufferedInputStream(System.in));
String st = "abcdefg";
System.out.println(st.charAt(0)); // st.charAt(i)就相当于st[i].
char [] ch;
ch = st.toCharArray(); // 字符串转换为字符数组.
for (i = 0; i < ch.length; i++) ch[i] += 1;
System.out.println(ch); // 输入为“bcdefgh”.
if (st.startsWith("a")) // 如果字符串以'0'开头.
{
st = st.substring(1); // 则从第1位开始copy(开头为第0位).
}
}
}
4. 高精度
BigInteger和BigDecimal可以说是acmer选择java的首要原因。
函数:add, subtract, divide, mod, compareTo等,其中加减乘除模都要求是
BigInteger(BigDecimal)和BigInteger(BigDecimal)之间的运算,所以需要把int(double)类型
转换为BigInteger(BigDecimal),用函数BigInteger.valueOf().
BigInteger 和 BigDecimal 是在java.math包中已有的类,前者表示整数,后者表示浮点数
import java.math.* // 需要引入 java.math 包
BigInteger a = BigInteger.valueOf(100);
BigInteger b = BigInteger.valueOf(50);
BigInteger c = a.add(b) // c = a + b;
//主要有以下方法可以使用:
BigInteger add(BigInteger other)
BigInteger subtract(BigInteger other)
BigInteger multiply(BigInteger other)
BigInteger divide(BigInteger other)
BigInteger mod(BigInteger other)
int compareTo(BigInteger other)
static BigInteger valueOf(long x)
//输出数字时直接使用 System.out.println(a) 即可
例程:
import java.io.*;
import java.math.*;
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner cin = new Scanner (new BufferedInputStream(System.in));
int a = 123, b = 456, c = 7890;
BigInteger x, y, z, ans;
x = BigInteger.valueOf(a);
y = BigInteger.valueOf(b);
z = BigInteger.valueOf(c);
ans = x.add(y);
System.out.println(ans);
ans = z.divide(y);
System.out.println(ans);
ans = x.mod(z);
System.out.println(ans);
if (pareTo(x) == 0)
System.out.println("1");
}
}
5. 进制转换
java很强大的一个功能。
函数:
String st = Integer.toString(num, base); // 把num当做10进制的数转成base进制的st(base <= 35).
// 把st当做base进制,转成10进制的int(parseInt有两个参数,第一个为要转的字符串,第二个为说明是什么进制).
int num = Integer.parseInt(st, base);
BigInter m = new BigInteger(st, base); // st是字符串,base是st的进制.
由于Unicode兼容ASCII(0~255),因此,上面得到的Unicode就是ASCII。
java中进行二进制,八进制,十六进制,十进制间进行相互转换
Integer.toHexString(int i)十进制转成十六进制
Integer.toOctalString(int i) 十进制转成八进制
Integer.toBinaryString(int i)十进制转成二进制
Integer.valueOf("FFFF",16).toString()十六进制转成十进制
Integer.valueOf("876",8).toString()八进制转成十进制
Integer.valueOf("0101",2).toString()二进制转十进制
至于转换成二进制或其他进制,Java API提供了方便函数,你可以查Java的API手册。
以字符a的ASCII为例:
int i = 'a';
String iBin = Integer.toBinaryString(i);//二进制
String iHex = Integer.toHexString(i);//十六进制
String iOct = Integer.toOctalString(i);//八进制
String iWoKao = Integer.toString(i,3);//三进制或任何你想要的35进制以下的进制DEC
有什么方法可以直接将2,8,16进制直接转换为10进制的吗?
java.lang.Integer类
parseInt(String s, int radix)
使用第二个参数指定的基数,将字符串参数解析为有符号的整数。
examples from jdk:
parseInt("0", 10) returns 0
parseInt("473", 10) returns 473
parseInt("-0", 10) returns 0
parseInt("-FF", 16) returns -255
parseInt("1100110", 2) returns 102
parseInt("2147483647", 10) returns 2147483647
parseInt("-2147483648", 10) returns -2147483648
parseInt("2147483648", 10) throws a NumberFormatException
parseInt("99", 8) throws a NumberFormatException
parseInt("Kona", 10) throws a NumberFormatException
parseInt("Kona", 27) returns 411787
进制转换如何写(二,八,十六)不用算法
Integer.toBinaryString
Integer.toOctalString
Integer.toHexString
例一:
public class Test{
public static void main(String args[]){
int i=100;
String binStr=Integer.toBinaryString(i);
String otcStr=Integer.toOctalString(i);
String hexStr=Integer.toHexString(i);
System.out.println(binStr);
例二:
public class TestStringFormat {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("usage: java TestStringFormat <a number>");
System.exit(0);
}
Integer factor = Integer.valueOf(args[0]);
String s;
s = String.format("%d", factor);
System.out.println(s);
s = String.format("%x", factor);
System.out.println(s);
s = String.format("%o", factor);
System.out.println(s);
}
}
各种数字类型转换成字符串型:
String s = String.valueOf( value); // 其中 value 为任意一种数字类型。
字符串型转换成各种数字类型:
String s = "169";
byte b = Byte.parseByte( s );
short t = Short.parseShort( s );
int i = Integer.parseInt( s );
long l = Long.parseLong( s );
Float f = Float.parseFloat( s );
Double d = Double.parseDouble( s );
数字类型与数字类对象之间的转换:
byte b = 169;
Byte bo = new Byte( b );
b = bo.byteValue();
short t = 169;
Short to = new Short( t );
t = to.shortValue();
int i = 169;
b = bo.byteValue();
short t = 169;
Short to = new Short( t );
t = to.shortValue();
int i = 169;
Integer io = new Integer( i );
i = io.intValue();
long l = 169;
Long lo = new Long( l );
l = lo.longValue();
float f = 169f;
Float fo = new Float( f );
f = fo.floatValue();
double d = 169f;
Double dObj = new Double( d );
d = dObj.doubleValue();
6. 简单排序
函数:Arrays.sort();
例程:
import java.io.*;
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner cin = new Scanner (new BufferedInputStream(System.in));
int n = cin.nextInt();
int a[] = new int [n];
for (int i = 0; i < n; i++)
a[i] = cin.nextInt();
Arrays.sort(a);
for (int i = 0; i < n; i++)
System.out.print(a[i] + " ");
}
}
8.调用递归(或其他动态方法)
在主类中 main 方法必须是 public static void 的,在 main 中调用非static类时会有警告信息,
可以先建立对象,然后通过对象调用方法:
public class Main {
void dfs(int a)
{
if () return;
dfs(a+1);
}
public static void main(String args[])
{
Main e = new Main();
e.dfs(0);
}
}
其他注意的事项:
(1) Java 是面向对象的语言,思考方法需要变换一下,里面的函数统称为方法,不要搞错。
(2) Java 里的数组有些变动,多维数组的内部其实都是指针,所以Java不支持fill多维数组。
数组定义后必须初始化,如 int[] a = new int[100];
(3) 布尔类型为 boolean,只有true和false二值,在 if (...) / while (...) 等语句的条件中必须为boolean类型。
在C/C++中的 if (n % 2) ... 在Java中无法编译通过。
(4) 下面在java.util包里Arrays类的几个方法可替代C/C++里的memset、qsort/sort 和 bsearch:
Arrays.fill()
Arrays.sort()
Arrays.binarySearch()
虽然Java功能很强大,但不能完全依赖他,毕竟C和C++还是ACM/ICPC的主流语言,适当地使用才能有效提高比赛中的成绩。。。
后面是基本算法的ava实现
1 Fibonacci 斐波那契
Fibonacci为1200年代的欧洲数学家,在他的著作中曾经提到:若有一只兔子每个月生一只小兔子,一个月后小兔子也开始生产。起初只有一只兔子,一个月后就有两只兔子,两个月后有三只兔子,三个月后有五只兔子(小兔子投入生产)……
这就是Fibonacci数列,一般习惯称之为费式数列,例如:1,1,2,3,5,8,13,21,34,55,89,……
Java代码
public class Fibonacci {
public static void main(String[] args) {
展开阅读全文