重庆分公司,新征程启航

为企业提供网站建设、域名注册、服务器等服务

java代码大全经典,Java经典代码

需求50句以上的JAVA代码,并带注解

Java文件操作大全

创新互联建站专注于曲周企业网站建设,响应式网站开发,商城开发。曲周网站建设公司,为曲周等地区提供建站服务。全流程按需定制制作,专业设计,全程项目跟踪,创新互联建站专业和态度为您提供的服务

1.创建文件夹

//import java.io.*;

File myFolderPath = new File(%%1);

try {

if (!myFolderPath.exists()) {

myFolderPath.mkdir();

}

}

catch (Exception e) {

System.out.println("新建目录操作出错");

e.printStackTrace();

}

2.创建文件

//import java.io.*;

File myFilePath = new File(%%1);

try {

if (!myFilePath.exists()) {

myFilePath.createNewFile();

}

FileWriter resultFile = new FileWriter(myFilePath);

PrintWriter myFile = new PrintWriter(resultFile);

myFile.println(%%2);

resultFile.close();

}

catch (Exception e) {

System.out.println("新建文件操作出错");

e.printStackTrace();

}

3.删除文件

//import java.io.*;

File myDelFile = new File(%%1);

try {

myDelFile.delete();

}

catch (Exception e) {

System.out.println("删除文件操作出错");

e.printStackTrace();

}

4.删除文件夹

//import java.io.*;

File delFolderPath = new File(%%1);

try {

delFolderPath.delete(); //删除空文件夹

}

catch (Exception e) {

System.out.println("删除文件夹操作出错");

e.printStackTrace();

}

5.删除一个文件下夹所有的文件夹

//import java.io.*;

File delfile=new File(%%1);

File[] files=delfile.listFiles();

for(int i=0;ifiles.length;i++){

if(files[i].isDirectory()){

files[i].delete();

}

}

6.清空文件夹

//import java.io.*;

File delfilefolder=new File(%%1);

try {

if (!delfilefolder.exists()) {

delfilefolder.delete();

}

delfilefolder.mkdir();

}

catch (Exception e) {

System.out.println("清空目录操作出错");

e.printStackTrace();

}

7.读取文件

//import java.io.*;

// 逐行读取数据

FileReader fr = new FileReader(%%1);

BufferedReader br = new BufferedReader(fr);

String %%2 = br.readLine();

while (%%2 != null) {

%%3

%%2 = br.readLine();

}

br.close();

fr.close();

8.写入文件

//import java.io.*;

// 将数据写入文件

try {

FileWriter fw = new FileWriter(%%1);

fw.write(%%2);

fw.flush();

fw.close();

} catch (IOException e) {

e.printStackTrace();

}

9.写入随机文件

//import java.io.*;

try {

RandomAcessFile logFile=new RandomAcessFile(%%1,"rw");

long lg=logFile.length();

logFile.seek(%%2);

logFile.writeByte(%%3);

}catch(IOException ioe){

System.out.println("无法写入文件:"+ioe.getMessage());

}

10.读取文件属性

//import java.io.*;

// 文件属性的取得

File af = new File(%%1);

if (af.exists()) {

System.out.println(f.getName() + "的属性如下: 文件长度为:" + f.length());

System.out.println(f.isFile() ? "是文件" : "不是文件");

System.out.println(f.isDirectory() ? "是目录" : "不是目录");

System.out.println(f.canRead() ? "可读取" : "不");

System.out.println(f.canWrite() ? "是隐藏文件" : "");

System.out.println("文件夹的最后修改日期为:" + new Date(f.lastModified()));

} else {

System.out.println(f.getName() + "的属性如下:");

System.out.println(f.isFile() ? "是文件" : "不是文件");

System.out.println(f.isDirectory() ? "是目录" : "不是目录");

System.out.println(f.canRead() ? "可读取" : "不");

System.out.println(f.canWrite() ? "是隐藏文件" : "");

System.out.println("文件的最后修改日期为:" + new Date(f.lastModified()));

}

if(f.canRead()){

%%2

}

if(f.canWrite()){

%%3

}

11.写入属性

//import java.io.*;

File filereadonly=new File(%%1);

try {

boolean b=filereadonly.setReadOnly();

}

catch (Exception e) {

System.out.println("拒绝写访问:"+e.printStackTrace());

}

12.枚举一个文件夹中的所有文件

//import java.io.*;

//import java.util.*;

LinkedListString folderList = new LinkedListString();

folderList.add(%%1);

while (folderList.size() 0) {

File file = new File(folderList.peek());

folderList.removeLast();

File[] files = file.listFiles();

ArrayListFile fileList = new ArrayListFile();

for (int i = 0; i files.length; i++) {

if (files[i].isDirectory()) {

folderList.add(files[i].getPath());

} else {

fileList.add(files[i]);

}

}

for (File f : fileList) {

%%2=f.getAbsoluteFile();

%%3

}

}

13.复制文件夹

//import java.io.*;

//import java.util.*;

LinkedListString folderList = new LinkedListString();

folderList.add(%%1);

LinkedListString folderList2 = new LinkedListString();

folderList2.add(%%2+ %%1.substring(%%1.lastIndexOf("\\")));

while (folderList.size() 0) {

(new File(folderList2.peek())).mkdirs(); // 如果文件夹不存在 则建立新文件夹

File folders = new File(folderList.peek());

String[] file = folders.list();

File temp = null;

try {

for (int i = 0; i file.length; i++) {

if (folderList.peek().endsWith(File.separator)) {

temp = new File(folderList.peek() + File.separator

+ file[i]);

} else {

temp = new File(folderList.peek() + File.separator

+ file[i]);

}

if (temp.isFile()) {

FileInputStream input = new FileInputStream(temp);

FileOutputStream output = new FileOutputStream(

folderList2.peek() + File.separator

+ (temp.getName()).toString());

byte[] b = new byte[5120];

int len;

while ((len = input.read(b)) != -1) {

output.write(b, 0, len);

}

output.flush();

output.close();

input.close();

}

if (temp.isDirectory()) {// 如果是子文件夹

for (File f : temp.listFiles()) {

if (f.isDirectory()) {

folderList.add(f.getPath());

folderList2.add(folderList2.peek()

+ File.separator + f.getName());

}

}

}

}

} catch (Exception e) {

//System.out.println("复制整个文件夹内容操作出错");

e.printStackTrace();

}

folderList.removeFirst();

folderList2.removeFirst();

}

14.复制一个文件夹下所有的文件夹到另一个文件夹下

//import java.io.*;

//import java.util.*;

File copyfolders=new File(%%1);

File[] copyfoldersList=copyfolders.listFiles();

for(int k=0;kcopyfoldersList.length;k++){

if(copyfoldersList[k].isDirectory()){

ArrayListStringfolderList=new ArrayListString();

folderList.add(copyfoldersList[k].getPath());

ArrayListStringfolderList2=new ArrayListString();

folderList2.add(%%2+"/"+copyfoldersList[k].getName());

for(int j=0;jfolderList.length;j++){

(new File(folderList2.get(j))).mkdirs(); //如果文件夹不存在 则建立新文件夹

File folders=new File(folderList.get(j));

String[] file=folders.list();

File temp=null;

try {

for (int i = 0; i file.length; i++) {

if(folderList.get(j).endsWith(File.separator)){

temp=new File(folderList.get(j)+"/"+file[i]);

}

else{

temp=new File(folderList.get(j)+"/"+File.separator+file[i]);

}

FileInputStream input = new FileInputStream(temp);

if(temp.isFile()){

FileInputStream input = new FileInputStream(temp);

FileOutputStream output = new FileOutputStream(folderList2.get(j) + "/" +

(temp.getName()).toString());

byte[] b = new byte[5120];

int len;

while ( (len = input.read(b)) != -1) {

output.write(b, 0, len);

}

output.flush();

output.close();

input.close();

}

if(temp.isDirectory()){//如果是子文件夹

folderList.add(folderList.get(j)+"/"+file[i]);

folderList2.add(folderList2.get(j)+"/"+file[i]);

}

}

}

catch (Exception e) {

System.out.println("复制整个文件夹内容操作出错");

e.printStackTrace();

}

}

}

}

15.移动文件夹

//import java.io.*;

//import java.util.*;

LinkedListString folderList = new LinkedListString();

folderList.add(%%1);

LinkedListString folderList2 = new LinkedListString();

folderList2.add(%%2 + %%1.substring(%%1.lastIndexOf("\\")));

while (folderList.size() 0) {

(new File(folderList2.peek())).mkdirs(); // 如果文件夹不存在 则建立新文件夹

File folders = new File(folderList.peek());

String[] file = folders.list();

File temp = null;

try {

for (int i = 0; i file.length; i++) {

if (folderList.peek().endsWith(File.separator)) {

temp = new File(folderList.peek() + File.separator

+ file[i]);

} else {

temp = new File(folderList.peek() + File.separator

+ file[i]);

}

if (temp.isFile()) {

FileInputStream input = new FileInputStream(temp);

FileOutputStream output = new FileOutputStream(

folderList2.peek() + File.separator

+ (temp.getName()).toString());

byte[] b = new byte[5120];

int len;

while ((len = input.read(b)) != -1) {

output.write(b, 0, len);

}

output.flush();

output.close();

input.close();

if (!temp.delete())

System.out.println("删除单个文件操作出错!");

}

if (temp.isDirectory()) {// 如果是子文件夹

for (File f : temp.listFiles()) {

if (f.isDirectory()) {

folderList.add(f.getPath());

folderList2.add(folderList2.peek()

+ File.separator + f.getName());

}

}

}

}

} catch (Exception e) {

// System.out.println("复制整个文件夹内容操作出错");

e.printStackTrace();

}

folderList.removeFirst();

folderList2.removeFirst();

}

File f = new File(%%1);

if (!f.delete()) {

for (File file : f.listFiles()) {

if (file.list().length == 0) {

System.out.println(file.getPath());

file.delete();

}

}

}

16.移动一个文件夹下所有的文件夹到另一个目录下

//import java.io.*;

//import java.util.*;

File movefolders=new File(%%1);

File[] movefoldersList=movefolders.listFiles();

for(int k=0;kmovefoldersList.length;k++){

if(movefoldersList[k].isDirectory()){

ArrayListStringfolderList=new ArrayListString();

folderList.add(movefoldersList[k].getPath());

ArrayListStringfolderList2=new ArrayListString();

folderList2.add(%%2+"/"+movefoldersList[k].getName());

for(int j=0;jfolderList.length;j++){

(new File(folderList2.get(j))).mkdirs(); //如果文件夹不存在 则建立新文件夹

File folders=new File(folderList.get(j));

String[] file=folders.list();

File temp=null;

try {

for (int i = 0; i file.length; i++) {

if(folderList.get(j).endsWith(File.separator)){

temp=new File(folderList.get(j)+"/"+file[i]);

}

else{

temp=new File(folderList.get(j)+"/"+File.separator+file[i]);

}

FileInputStream input = new FileInputStream(temp);

if(temp.isFile()){

FileInputStream input = new FileInputStream(temp);

FileOutputStream output = new FileOutputStream(folderList2.get(j) + "/" +

(temp.getName()).toString());

byte[] b = new byte[5120];

int len;

while ( (len = input.read(b)) != -1) {

output.write(b, 0, len);

}

output.flush();

output.close();

input.close();

temp.delete();

}

if(temp.isDirectory()){//如果是子文件夹

folderList.add(folderList.get(j)+"/"+file[i]);

folderList2.add(folderList2.get(j)+"/"+file[i]);

}

}

}

catch (Exception e) {

System.out.println("复制整个文件夹内容操作出错");

e.printStackTrace();

}

}

movefoldersList[k].delete();

}

}

17.以一个文件夹的框架在另一个目录创建文件夹和空文件

//import java.io.*;

//import java.util.*;

boolean b=false;//不创建空文件

ArrayListStringfolderList=new ArrayListString();

folderList.add(%%1);

ArrayListStringfolderList2=new ArrayListString();

folderList2.add(%%2);

for(int j=0;jfolderList.length;j++){

(new File(folderList2.get(j))).mkdirs(); //如果文件夹不存在 则建立新文件夹

File folders=new File(folderList.get(j));

String[] file=folders.list();

File temp=null;

try {

for (int i = 0; i file.length; i++) {

if(folderList.get(j).endsWith(File.separator)){

temp=new File(folderList.get(j)+"/"+file[i]);

}

else{

temp=new File(folderList.get(j)+"/"+File.separator+file[i]);

}

FileInputStream input = new FileInputStream(temp);

if(temp.isFile()){

if (b) temp.createNewFile();

}

if(temp.isDirectory()){//如果是子文件夹

folderList.add(folderList.get(j)+"/"+file[i]);

folderList2.add(folderList2.get(j)+"/"+file[i]);

}

}

}

catch (Exception e) {

System.out.println("复制整个文件夹内容操作出错");

e.printStackTrace();

}

}

18.复制文件

//import java.io.*;

int bytesum = 0;

int byteread = 0;

File oldfile = new File(%%1);

try {

if (oldfile.exists()) { //文件存在时

FileInputStream inStream = new FileInputStream(oldfile); //读入原文件

FileOutputStream fs = new FileOutputStream(new File(%%2,oldfile.getName()));

byte[] buffer = new byte[5120];

int length;

while ( (byteread = inStream.read(buffer)) != -1) {

bytesum += byteread; //字节数 文件大小

System.out.println(bytesum);

fs.write(buffer, 0, byteread);

}

inStream.close();

}

}

catch (Exception e) {

System.out.println("复制单个文件操作出错");

e.printStackTrace();

}

19.复制一个文件夹下所有的文件到另一个目录

//import java.io.*;

File copyfiles=new File(%%1);

File[] files=copyfiles.listFiles();

for(int i=0;ifiles.length;i++){

if(!files[i].isDirectory()){

int bytesum = 0;

int byteread = 0;

try {

InputStream inStream = new FileInputStream(files[i]); //读入原文件

FileOutputStream fs = new FileOutputStream(new File(%%2,files[i].getName());

byte[] buffer = new byte[5120];

int length;

while ( (byteread = inStream.read(buffer)) != -1) {

bytesum += byteread; //字节数 文件大小

System.out.println(bytesum);

fs.write(buffer, 0, byteread);

}

inStream.close();

} catch (Exception e) {

System.out.println("复制单个文件操作出错");

e.printStackTrace();

}

}

}

20.提取扩展名

String %%2=%%1.substring(%%1.lastIndexOf(".")+1);

java代码示例

importjava.awt.*;importjava.awt.event.*;classShopFrameextendsFrameimplementsActionListener{Labellabel1,label2,label3,label4;Buttonbutton1,button2,button3,button4,button5;TextAreatext;Panelpanel1,panel2;staticfloatsum=0.0f;ShopFrame(Strings){super(s);setLayout(newBorderLayout());label1=newLabel("面纸:3元",Label.LEFT);label2=newLabel("钢笔:5元",Label.LEFT);label3=newLabel("书:10元",Label.LEFT);label4=newLabel("袜子:8元",Label.LEFT);button1=newButton("加入购物车");button2=newButton("加入购物车");button3=newButton("加入购物车");button4=newButton("加入购物车");button5=newButton("查看购物车");text=newTextArea("商品有:"+"\n",5,10);text.setEditable(false);addWindowListener(newWindowAdapter(){publicvoidwindowClosing(WindowEvente){System.exit(0);}});button1.addActionListener(this);button2.addActionListener(this);button3.addActionListener(this);button4.addActionListener(this);button5.addActionListener(this);panel1=newPanel();panel2=newPanel();panel1.add(label1);panel1.add(button1);panel1.add(label2);panel1.add(button2);panel1.add(label3);panel1.add(button3);panel1.add(label4);panel1.add(button4);panel2.setLayout(newBorderLayout());panel2.add(button5,BorderLayout.NORTH);panel2.add(text,BorderLayout.SOUTH);this.add(panel1,BorderLayout.CENTER);this.add(panel2,BorderLayout.SOUTH);setBounds(100,100,350,250);setVisible(true);validate();}publicvoidactionPerformed(ActionEvente){if(e.getSource()==button1){text.append("一个面纸、");sum=sum+3;}elseif(e.getSource()==button2){text.append("一只钢笔、");sum=sum+5;}elseif(e.getSource()==button3){text.append("一本书、");sum=sum+10;}elseif(e.getSource()==button4){text.append("一双袜子、");sum=sum+8;}elseif(e.getSource()==button5){text.append("\n"+"总价为:"+"\n"+sum);}}}publicclassShopping{publicstaticvoidmain(String[]args){newShopFrame("购物车");}}我没用Swing可能显示不出来你的效果。不满意得话我在给你编一个。

求一个简单又有趣的JAVA小游戏代码

具体如下:

连连看的小源码

package Lianliankan;

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class lianliankan implements ActionListener

{

JFrame mainFrame; //主面板

Container thisContainer;

JPanel centerPanel,southPanel,northPanel; //子面板

JButton diamondsButton[][] = new JButton[6][5];//游戏按钮数组

JButton exitButton,resetButton,newlyButton; //退出,重列,重新开始按钮

JLabel fractionLable=new JLabel("0"); //分数标签

JButton firstButton,secondButton; //

分别记录两次62616964757a686964616fe59b9ee7ad9431333335326239被选中的按钮

int grid[][] = new int[8][7];//储存游戏按钮位置

static boolean pressInformation=false; //判断是否有按钮被选中

int x0=0,y0=0,x=0,y=0,fristMsg=0,secondMsg=0,validateLV; //游戏按钮的位置坐标

int i,j,k,n;//消除方法控制

代码(code)是程序员用开发工具所支持的语言写出来的源文件,是一组由字符、符号或信号码元以离散形式表示信息的明确的规则体系。

对于字符和Unicode数据的位模式的定义,此模式代表特定字母、数字或符号(例如 0x20 代表一个空格,而 0x74 代表字符“t”)。一些数据类型每个字符使用一个字节;每个字节可以具有 256 个不同的位模式中的一个模式。

在计算机中,字符由不同的位模式(ON 或 OFF)表示。每个字节有 8 位,这 8 位可以有 256 种不同的 ON 和 OFF 组合模式。对于使用 1 个字节存储每个字符的程序,通过给每个位模式指派字符可表示最多 256 个不同的字符。2 个字节有 16 位,这 16 位可以有 65,536 种唯一的 ON 和 OFF 组合模式。使用 2 个字节表示每个字符的程序可表示最多 65,536 个字符。

单字节代码页是字符定义,这些字符映射到每个字节可能有的 256 种位模式中的每一种。代码页定义大小写字符、数字、符号以及 !、@、#、% 等特殊字符的位模式。每种欧洲语言(如德语和西班牙语)都有各自的单字节代码页。

虽然用于表示 A 到 Z 拉丁字母表字符的位模式在所有的代码页中都相同,但用于表示重音字符(如"é"和"á")的位模式在不同的代码页中却不同。如果在运行不同代码页的计算机间交换数据,必须将所有字符数据由发送计算机的代码页转换为接收计算机的代码页。如果源数据中的扩展字符在接收计算机的代码页中未定义,那么数据将丢失。

如果某个数据库为来自许多不同国家的客户端提供服务,则很难为该数据库选择这样一种代码页,使其包括所有客户端计算机所需的全部扩展字符。而且,在代码页间不停地转换需要花费大量的处理时间。

java线程的经典代码

package threadgroup;

class ThreadDemo3 extends Thread {

private String name;

private int delay;

public ThreadDemo3(String sname, int i_delay) {

name = sname;

delay = i_delay;

}

public void run() {

try {

sleep(delay);

} catch (InterruptedException e) {

}

System.out.println("多线程测试!\n" + name + "\n" + delay);

}

}

public class testMyThread {

public static void main(String[] args) {

ThreadDemo3 th1,th2,th3;

th1 = new ThreadDemo3("线程1", (int) (Math.random() * 900));

th2 = new ThreadDemo3("线程2", (int) (Math.random() * 900));

th3 = new ThreadDemo3("线程3", (int) (Math.random() * 900));

th1.start();

th2.start();

th3.start();

}

}

package threadgroup;

public class threadDemo {

public static void main(String[] args) {

Thread t = Thread.currentThread();

t.setName("你好吗?");

System.out.println("正在进行的Thread是:" + t);

try {

for (int i = 0; i 5; i++) {

System.out.println("我不叫穆继超" + i);

Thread.sleep(3000);

}

} catch (Exception e) {

// TODO: handle exception

System.out.println("Thread has wrong" + e.getMessage());

}

}

}

package threadgroup;

public class threadDemo2 implements Runnable {

public threadDemo2() {

Thread t1 = Thread.currentThread();

t1.setName("第一个主进程");

System.out.println("正在运行" + t1);

Thread t2 = new Thread(this, "");

System.out.println("在创建一个进程");

t2.start();

try {

System.out.println("使他进入第一个睡眠状态");

Thread.sleep(2000);

} catch (InterruptedException e) {

System.out.println("Thread has wrong" + e.getMessage());

}

System.out.println("退出第一个进程");

}

public void run() {

try {

for (int i = 0; i 5; i++) {

System.out.println("进程" + i);

Thread.sleep(3000);

}

} catch (InterruptedException e) {

// TODO: handle exception

System.out.println("Thread has wrong" + e.getMessage());

}

System.out.println("退出第二个进程");

}

public static void main(String[] args) {

new threadDemo2();

}

}

有什么io方面的java经典代码

package IO;

import java.io.*;

public class FileDirectoryDemo {

public static void main(String[] args) {

// 如果没有指定参数,则缺省为当前目录。

if (args.length == 0) {

args = new String[] { "." };

}

try {

// 新建指定目录的File对象。

File currentPath = new File(args[0]);

// 在指定目录新建temp目录的File对象。

File tempPath = new File(currentPath, "temp");

// 用“tempPath”对象在指定目录下创建temp目录。

tempPath.mkdir();

// 在temp目录下创建两个文件。

File temp1 = new File(tempPath, "temp1.txt");

temp1.createNewFile();

File temp2 = new File(tempPath, "temp2.txt");

temp2.createNewFile();

// 递归显示指定目录的内容。

System.out.println("显示指定目录的内容");

listSubDir(currentPath);

// 更改文件名“temp1.txt”为“temp.txt”。

File temp1new = new File(tempPath, "temp.txt");

temp1.renameTo(temp1new);

// 递归显示temp子目录的内容。

System.out.println("更改文件名后,显示temp子目录的内容");

listSubDir(tempPath);

// 删除文件“temp2.txt”。

temp2.delete();

// 递归显示temp子目录的内容。

System.out.println("删除文件后,显示temp子目录的内容");

listSubDir(tempPath);

} catch (IOException e) {

System.err.println("IOException");

}

}

// 递归显示指定目录的内容。

static void listSubDir(File currentPath) {

// 取得指定目录的内容列表。

String[] fileNames = currentPath.list();

try {

for (int i = 0; i fileNames.length; i++) {

File f = new File(currentPath.getPath(), fileNames[i]);

// 如果是目录,则显示目录名后,递归调用,显示子目录的内容。

if (f.isDirectory()) {

// 以规范的路径格式显示目录。

System.out.println(f.getCanonicalPath());

// 递归调用,显示子目录。

listSubDir(f);

}

// 如果是文件,则显示文件名,不包含路径信息。

else {

System.out.println(f.getName());

}

}

} catch (IOException e) {

System.err.println("IOException");

}

}

}

package IO;

import java.io.*;

public class FileExample {

public FileExample() {

super();

}

public static void main(String[] args) {

try {

String outfile = "demoout.xml";

String infile = "demoin.xml";

/**

* 用FileOutputStream定义一个输入流文件,然后用BuferedOutputStream调用FileOutputStream对象生成一个缓冲输出流

然后用DataOutputStream调用BuferedOutputStream对象生成数据格式化输出流

*/

DataOutputStream dt=new DataOutputStream(new BufferedOutputStream(new FileOutputStream(outfile)));

BufferedWriter NewFile = new BufferedWriter(new OutputStreamWriter(dt, "GBK"));

// 对中文的处理

// 定义一个输入流

DataInputStream rafFile1 = new DataInputStream(new BufferedInputStream(new FileInputStream(infile)));

// 定义一个输入缓冲

BufferedReader rafFile = new BufferedReader(new InputStreamReader(rafFile1, "GBK"));

String xmlcontent = "";

char tag = 0;// 文件友字符0结束

while (tag != (char) (-1)) {

xmlcontent = xmlcontent + tag + rafFile.readLine() + '\n';

tag = (char) rafFile.read();

}

NewFile.write(xmlcontent);

NewFile.flush();

NewFile.close();

rafFile.close();

System.gc();

} catch (NullPointerException exc) {

exc.printStackTrace();

} catch (java.lang.IndexOutOfBoundsException outb) {

System.out.println(outb.getMessage());

outb.printStackTrace();

} catch (FileNotFoundException fex) {

System.out.println("fex" + fex.getMessage());

} catch (IOException iex) {

System.out.println("iex" + iex.getMessage());

}

}

}

package IO;

import java.io.*;

public class FileRandomRW {

// 需要输入的person数目。

public static int NUMBER = 3;

public static void main(String[] args) {

Persons[] people = new Persons[NUMBER];

people[0] = new Persons("张峰", 26, 2000, "N");

people[1] = new Persons("艳娜", 25, 50000, "Y");

people[2] = new Persons("李朋", 50, 7000, "F");

try {

DataOutputStream out = new DataOutputStream(new FileOutputStream(

"peoplerandom.dat"));

// 将人员数据保存至“peoplerandom.dat”二进制文件中。

writeData(people, out);

// 关闭流。

out.close();

// 从二进制文件“peoplerandom.dat”中逆序读取数据。

RandomAccessFile inOut = new RandomAccessFile("peoplerandom.dat",

"rw");

Persons[] inPeople = readDataReverse(inOut);

// 输出读入的数据。

System.out.println("原始数据:");

for (int i = 0; i inPeople.length; i++) {

System.out.println(inPeople[i]);

}

// 修改文件的第三条记录。

inPeople[2].setSalary(4500);

// 将修改结果写入文件。

inPeople[2].writeData(inOut, 3);

// 关闭流。

inOut.close();

// 从文件中读入的第三条记录,并输出,以验证修改结果。

RandomAccessFile in = new RandomAccessFile("peoplerandom.dat", "r");

Persons in3People = new Persons();

// 随机读第三条记录。

in3People.readData(in, 3);

// 关闭流。

in.close();

System.out.println("修改后的记录");

System.out.println(in3People);

} catch (IOException exception) {

System.err.println("IOException");

}

}

// 将数据写入输出流。

static void writeData(Persons[] p, DataOutputStream out) throws IOException {

for (int i = 0; i p.length; i++) {

p[i].writeData(out);

}

}

// 将数据从输入流中逆序读出。

static Persons[] readDataReverse(RandomAccessFile in) throws IOException {

// 获得记录数目。

int record_num = (int) (in.length() / Persons.RECORD_LENGTH);

Persons[] p = new Persons[record_num];

// 逆序读取。

for (int i = record_num - 1; i = 0; i--) {

p[i] = new Persons();

// 文件定位。

in.seek(i * Persons.RECORD_LENGTH);

p[i].readData(in, i + 1);

}

return p;

}

}

class Persons {

private String name;

private int age; // 4个字节

private double salary; // 8个字节

private String married;

public static final int NAME_LENGTH = 20; // 姓名长度

public static final int MARRIED_LENGTH = 2; // 婚否长度

public static final int RECORD_LENGTH = NAME_LENGTH * 2 + 4 + 8

+ MARRIED_LENGTH * 2;

public Persons() {

}

public Persons(String n, int a, double s) {

name = n;

age = a;

salary = s;

married = "F";

}

public Persons(String n, int a, double s, String m) {

name = n;

age = a;

salary = s;

married = m;

}

public String getName() {

return name;

}

public int getAge() {

return age;

}

public double getSalary() {

return salary;

}

public String getMarried() {

return married;

}

public String setName(String n) {

name = n;

return name;

}

public int setAge(int a) {

age = a;

return age;

}

public double setSalary(double s) {

salary = s;

return salary;

}

public String setMarried(String m) {

married = m;

return married;

}

// 设置输出格式。

public String toString() {

return getClass().getName() + "[name=" + name + ",age=" + age

+ ",salary=" + salary + ",married=" + married + "]";

}

// 写入一条固定长度的记录,即一个人的数据到输出流。

public void writeData(DataOutput out) throws IOException {

FixStringIO.writeFixString(name, NAME_LENGTH, out);

out.writeInt(age);

out.writeDouble(salary);

FixStringIO.writeFixString(married, MARRIED_LENGTH, out);

}

// 写入一条固定长度的记录到随机读取文件中。

private void writeData(RandomAccessFile out) throws IOException {

FixStringIO.writeFixString(name, NAME_LENGTH, out);

out.writeInt(age);

out.writeDouble(salary);

FixStringIO.writeFixString(married, MARRIED_LENGTH, out);

}

// 随机写入一条固定长度的记录到输出流的指定位置。

public void writeData(RandomAccessFile out, int n) throws IOException {

out.seek((n - 1) * RECORD_LENGTH);

writeData(out);

}

// 从输入流随机读入一条记录,即一个人的数据。

private void readData(RandomAccessFile in) throws IOException {

name = FixStringIO.readFixString(NAME_LENGTH, in);

age = in.readInt();

salary = in.readDouble();

married = FixStringIO.readFixString(MARRIED_LENGTH, in);

}

// 从输入流随机读入指定位置的记录。

public void readData(RandomAccessFile in, int n) throws IOException {

in.seek((n - 1) * RECORD_LENGTH);

readData(in);

}

}

// 对固定长度字符串从文件读出、写入文件

class FixStringIO {

// 读取固定长度的Unicode字符串。

public static String readFixString(int size, DataInput in)

throws IOException {

StringBuffer b = new StringBuffer(size);

int i = 0;

boolean more = true;

while (more i size) {

char ch = in.readChar();

i++;

if (ch == 0) {

more = false;

} else {

b.append(ch);

}

}

// 跳过剩余的字节。

in.skipBytes(2 * (size - i));

return b.toString();

}

// 写入固定长度的Unicode字符串。

public static void writeFixString(String s, int size, DataOutput out)

throws IOException {

int i;

for (i = 0; i size; i++) {

char ch = 0;

if (i s.length()) {

ch = s.charAt(i);

}

out.writeChar(ch);

}

}

}

package IO;

import java.io.*;

import java.util.*;

public class FileRW {

// 需要输入的person数目。

public static int NUMBER = 3;

public static void main(String[] args) {

Person[] people = new Person[NUMBER];

// 暂时容纳输入数据的临时字符串数组。

String[] field = new String[4];

// 初始化field数组。

for (int i = 0; i 4; i++) {

field[i] = "";

}

// IO操作必须捕获IO异常。

try {

// 用于对field数组进行增加控制。

int fieldcount = 0;

// 先使用System.in构造InputStreamReader,再构造BufferedReader。

BufferedReader stdin = new BufferedReader(new InputStreamReader(

System.in));

for (int i = 0; i NUMBER; i++) {

fieldcount = 0;

System.out.println("The number " + (i + 1) + " person");

System.out

.println("Enter name,age,salary,married(optional),please separate fields by ':'");

// 读取一行。

String personstr = stdin.readLine();

// 设置分隔符。

StringTokenizer st = new StringTokenizer(personstr, ":");

// 判断是否还有分隔符可用。

while (st.hasMoreTokens()) {

field[fieldcount] = st.nextToken();

fieldcount++;

}

// 如果输入married,则field[3]不为空,调用具有四个参数的Person构造函数。

if (field[3] != "") {

people[i] = new Person(field[0],

Integer.parseInt(field[1]), Double

.parseDouble(field[2]), field[3]);

// 置field[3]为空,以备下次输入使用。

field[3] = "";

}

// 如果未输入married,则field[3]为空,调用具有三个参数的Person构造函数。

else {

people[i] = new Person(field[0],

Integer.parseInt(field[1]), Double

.parseDouble(field[2]));

}

}

// 将输入的数据保存至“people.dat”文本文件中。

PrintWriter out = new PrintWriter(new BufferedWriter(

new FileWriter("people.dat")));

writeData(people, out);

// 关闭流。

out.close();

// 从文件“people.dat”读取数据。

BufferedReader in = new BufferedReader(new FileReader("people.dat"));

Person[] inPeople = readData(in);

// 关闭流。

in.close();

// 输出从文件中读入的数据。

for (int i = 0; i inPeople.length; i++) {

System.out.println(inPeople[i]);

}

} catch (IOException exception) {

System.err.println("IOException");

}

}

// 将所有数据写入输出流。

static void writeData(Person[] p, PrintWriter out) throws IOException {

// 写入记录条数,即人数。

out.println(p.length);

for (int i = 0; i p.length; i++) {

p[i].writeData(out);

}

}

// 将所有数据从输入流中读出。

static Person[] readData(BufferedReader in) throws IOException {

// 获取记录条数,即人数。

int n = Integer.parseInt(in.readLine());

Person[] p = new Person[n];

for (int i = 0; i n; i++) {

p[i] = new Person();

p[i].readData(in);

}

return p;

}

}

class Person {

private String name;

private int age;

private double salary;

private String married;

public Person() {

}

public Person(String n, int a, double s) {

name = n;

age = a;

salary = s;

married = "F";

}

public Person(String n, int a, double s, String m) {

name = n;

age = a;

salary = s;

married = m;

}

public String getName() {

return name;

}

public int getAge() {

return age;

}

public double getSalary() {

return salary;

}

public String getMarried() {

return married;

}

// 设置输出格式。

public String toString() {

return getClass().getName() + "[name=" + name + ",age=" + age

+ ",salary=" + salary + ",married=" + married + "]";

}

// 写入一条记录,即一个人的数据到输出流。

public void writeData(PrintWriter out) throws IOException {

// 格式化输出。

out.println(name + ":" + age + ":" + salary + ":" + married);

}

// 从输入流读入一条记录,即一个人的数据。

public void readData(BufferedReader in) throws IOException {

String s = in.readLine();

StringTokenizer t = new StringTokenizer(s, ":");

name = t.nextToken();

age = Integer.parseInt(t.nextToken());

salary = Double.parseDouble(t.nextToken());

married = t.nextToken();

}

}

package IO;

import java.io.*;

public class IOStreamExample {

public static void main(String[] args) throws IOException {

// 1. 读入一行数据:

BufferedReader in = new BufferedReader(new FileReader(

"FileStdRead.java"));

String s, s2 = new String();

while ((s = in.readLine()) != null) {

s2 += s + "\n";

}

in.close();

BufferedReader stdin = new BufferedReader(new InputStreamReader(

System.in));

System.out.print("Enter a line:");

System.out.println(stdin.readLine());

// 2. 从内存中读入

StringReader in2 = new StringReader(s2);

int c;

while ((c = in2.read()) != -1) {

System.out.print((char) c);

}

// 3. 格式化内存输入

try {

DataInputStream in3 = new DataInputStream(new ByteArrayInputStream(

s2.getBytes()));

while (true) {

System.out.print((char) in3.readByte());

}

} catch (EOFException e) {

System.err.println("End of stream");

}

// 4. 文件输入

try {

BufferedReader in4 = new BufferedReader(new StringReader(s2));

PrintWriter out1 = new PrintWriter(new BufferedWriter(

new FileWriter("IODemo.out")));

int lineCount = 1;

while ((s = in4.readLine()) != null) {

out1.println(lineCount++ + ": " + s);

}

out1.close();

} catch (EOFException e) {

System.err.println("End of stream");

}

// 5. 接收和保存数据

try {

DataOutputStream out2 = new DataOutputStream(

new BufferedOutputStream(new FileOutputStream("Data.txt")));

out2.writeDouble(3.14159);

out2.writeUTF("That was pi");

out2.writeDouble(1.41413);

out2.writeUTF("Square root of 2");

out2.close();

DataInputStream in5 = new DataInputStream(new BufferedInputStream(

new FileInputStream("Data.txt")));

System.out.println(in5.readDouble());

System.out.println(in5.readUTF());

System.out.println(in5.readDouble());

System.out.println(in5.readUTF());

} catch (EOFException e) {

throw new RuntimeException(e);

}

// 6. 随机读取文件内容

RandomAccessFile rf = new RandomAccessFile("rtest.dat", "rw");

for (int i = 0; i 10; i++) {

rf.writeDouble(i * 1.414);

}

rf.close();

rf = new RandomAccessFile("rtest.dat", "rw");

rf.seek(5 * 8);

rf.writeDouble(47.0001);

rf.close();

rf = new RandomAccessFile("rtest.dat", "r");

for (int i = 0; i 10; i++) {

System.out.println("Value " + i + ": " + rf.readDouble());

}

rf.close();

}

}

package IO;

import java.io.*;

/**

* p

* Title: JAVA进阶诀窍

* /p

*

* @author 张峰

* @version 1.0

*/

public class MakeDirectoriesExample {

private static void fileattrib(File f) {

System.out.println("绝对路径: " + f.getAbsolutePath() + "\n 可读属性: "

+ f.canRead() + "\n 可定属性: " + f.canWrite() + "\n 文件名: "

+ f.getName() + "\n 父目录: " + f.getParent() + "\n 当前路径: "

+ f.getPath() + "\n 文件长度: " + f.length() + "\n 最后更新日期: "

+ f.lastModified());

if (f.isFile()) {

System.out.println("输入的是一个文件");

} else if (f.isDirectory()) {

System.out.println("输入的是一个目录");

}

}

public static void main(String[] args) {

if (args.length 1) {

args = new String[3];

}

args[0] = "d";

args[1] = "test1.txt";

args[2] = "test2.txt";

File old = new File(args[1]), rname = new File(args[2]);

old.renameTo(rname);

fileattrib(old);

fileattrib(rname);

int count = 0;

boolean del = false;

if (args[0].equals("d")) {

count++;

del = true;

}

count--;

while (++count args.length) {

File f = new File(args[count]);

if (f.exists()) {

System.out.println(f + " 文件己经存在");

if (del) {

System.out.println("删除文件" + f);

f.delete();

}

} else { // 如果文件不存在

if (!del) {

f.mkdirs();

System.out.println("创建文件: " + f);

}

}

fileattrib(f);

}

}

}

给段最简单的java代码 让我新手看一下

最简单的java代码肯定就是这个了,如下:

public class MyFirstApp

{

public static void main(String[] args)

{

System.out.print("Hello world");

}

}

“hello world”就是应该是所有学java的新手看的第一个代码了。如果是零基础的新手朋友们可以来我们的java实验班试听,有免费的试听课程帮助学习java必备基础知识,有助教老师为零基础的人提供个人学习方案,学习完成后有考评团进行专业测试,帮助测评学员是否适合继续学习java,15天内免费帮助来报名体验实验班的新手快速入门java,更好的学习java!


当前标题:java代码大全经典,Java经典代码
标题URL:http://cqcxhl.com/article/dsssooe.html

其他资讯

在线咨询
服务热线
服务热线:028-86922220
TOP