0722

来源:互联网 发布:sonar.java.binaries 编辑:程序博客网 时间:2024/06/05 01:08

1.打印只包含13579的乘法口诀,

并把结果输出到一个文件中;

拓展:输入若干个数字

求出它们的所有乘积结果并把结果输出到文件;

 

package com.xuyilong.IOTest;

 

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.OutputStream;

import java.util.Scanner;

 

 

 

public class Test2 {

 

public static void main(String[] args) {

OutputStream os=null; //建立一个OutputStream对象os

try {

File f=new File("f:/test/222.txt"); //建立一个File对象f

os=new FileOutputStream(f); //实例一个FileOutputStream对象赋值给os

if (!f.exists()) { //不存在就新建一个文件

f.createNewFile();

}

// os.write(printTable(0), 0, printTable(0).length); //把数据写入222.txt  .lengthbyte数组的长度

os.write(printTable(1), 0, printTable(1).length);

os.write(printNum());

System.out.println("写入成功!"); //提示信息

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}finally {

try {

os.close(); //关闭流

} catch (IOException e) {

e.printStackTrace();

}

}

}

static byte[] printTable(int x){ //输出99乘法表,x控制输出奇数偶数

String str=new String(); //建立一个字符串对象str

for (int i = 1; i < 10; i++) {

if (i % 2 == x) {

for (int j = 1; j < i + 1; j++) {

str=str+i + "*" + j + "=" + (i * j) + "\t"; //把乘法表存进str

}

str=str+"\r\n"; //txt文件的换行符

}

}

byte[] b=str.getBytes(); //str字符串转成byte类型,用byte数组存储

return b; //返回byte数组

}

 

static byte[] printNum(){

Scanner sc=new Scanner(System.in);

int s=0,i=0;

String str="";

while ((i=sc.nextInt())!=0) {

if (s==0) {

s=i;

str=""+i;

}else {

s*=i;

str=str+"*"+i;

}

}

sc.close();

return ("\r\n"+str+"="+s).getBytes();

}

}

 

 

2.自定义复制

输入文件路径a和文件路径b,把文件从a复制到b之下。

 

 

tips:通过scanner输入两个路径,一个是需要copy的路径,一个是copy到的路径

package com.xuyilong.IOTest;

 

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.util.Scanner;

 

 

public class CopyTest {

 

public static void main(String[] args) {

copyFile();

}

 

static void copyFile(){

System.out.println("输入需要复制的文件路径:(格式如:F:/test/aaa/aaa.txt");

Scanner sc=new Scanner(System.in);

String str1=sc.nextLine();

File f1=new File(str1);

System.out.println("输入文件复制到的目标路径:(格式如:F:/test");

String str2=sc.nextLine()+"/"+f1.getName();

File f2=new File(str2);

if (!f2.exists()) {

try {

f2.createNewFile();

} catch (IOException e) {

e.printStackTrace();

}

}

InputStream is=null;

OutputStream os=null;

byte[] b=new byte[500];

try {

is=new FileInputStream(f1);

os=new FileOutputStream(f2);

while (is.read(b)!=-1) {

os.write(b);

}

os.flush();

System.out.println("复制成功!");

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}finally {

sc.close();

try {

is.close();

os.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

 

 

0 0