要求:实现从控制台接收一些字符串,写入文件中,当输入”exit”,停止!
-------------------------------------------------------------------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 TestIO1 { public static void main(String[] args) {
Scanner input=new Scanner(System.in);
//1建立文件关联
File f=new File("F:/S2专属。/JAVA/IO回家作业/a.txt");
//2创建输出字节流
try {
OutputStream fos=new FileOutputStream(f);
//3.利用流对文件进行写操作
byte[] b=new byte[10];
fos.write(b);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
//4.流的关闭
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}}
-------------------------------------------------------------------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 TestIO1 { public static void main(String[] args) {
Scanner input=new Scanner(System.in);
//1建立文件关联
File f=new File("F:/S2专属。/JAVA/IO回家作业/a.txt");
//2创建输出字节流
try {
OutputStream fos=new FileOutputStream(f);
//3.利用流对文件进行写操作
byte[] b=new byte[10];
fos.write(b);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
//4.流的关闭
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}}
//要求:实现从控制台接收一些字符串,写入文件中,当输入”exit”,停止!import java.io.File;
import java.util.Scanner;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileNotFoundException;public class Test{
private final static String FILENAME = "C:/ricky.txt";
public static void main(String[] args){
System.out.println("Input content to the File:" + FILENAME);
System.out.println("Input 'exit' to exit the program!");
System.out.println("------------------------------------------"); Scanner keyboard = new Scanner(System.in); String content = null; File file = new File(FILENAME);
FileOutputStream fos = null; try{
fos = new FileOutputStream(file,true);
}catch(FileNotFoundException e){
System.err.println(e);
System.exit(1);
} while(true){
content = keyboard.nextLine();
if(content.equals("exit")){
System.out.println("Program exit!");
try{
fos.flush();
fos.close();
}catch(IOException e){
System.err.println(e);
}
System.exit(0);
}
try{
fos.write(content.getBytes());
}catch(IOException e){
System.err.println(e);
System.exit(1);
} }
}
}