Java 將字符串輸入文件中
題目介紹
從鍵盤輸入一個字符串,將小寫字母全部轉換成大寫字母,然後輸出到一個磁盤文件"test"中保存
思路分析
思路比較簡單,先用Scanner對象獲得一個字符串。然後創建文件,然後在將字符串輸入到指定的文件中
使用類的對象
Java IO使用原則:
按照數據來源(去向)分類:
1.是文件:FileInputStream,FileOutputStream,FileReader,FileWriter
2.是byte[]:ByteArrayInputStream,ByteArrayOutputStream
3.是Char[]:CharArrayReader,CharArrayWriter
5.網絡數據流:InputStream,OutputStram,Reader,Writer
按是否格式化輸出
1.要格式化輸出:PrintStream PrintWriter
按是否要緩沖分:
要緩沖:BufferedInputStream,BufferedOutputStream,BufferOutputStream,BufferWriter
按照數據格式分:
1.二進制格式(只要不能七確定是純文本的):InputStream,OutputStream以其所有帶Stream結束的子類
按輸入輸出分:
1.輸出:Reader,InputStream類型的子類
2.輸出:Writer,OutputStream類型的子類
特殊需要:
1.從Stream到Reader,Writer的轉換器,InputStreamReader,OutputStreamWriter
2.對象的出入輸出:ObjectInputStream,ObjectOutputStream
3.進程間通信:PipeInputStream,PipeOutputStream,PipeWriter,PipeWriter
決定使用哪個類以及構造進程的準組:
1.考慮最原始的數據格式是什麽
2.是輸入還是輸出
3.是否需要轉換流
4.數據的去向
5.是否需要緩沖
6.是否需要格式化輸出。
Java.io.Reader和java.io.InputStream組成了Java輸入類。Reader用於讀入16位字符,也就是Unicode編碼字符,而InputStream用於讀入ASCII字符和二進制數據。
對應的輸出類也有差不多的區別。
import java.io.*;
import java.util.Scanner;
public class Test{
private String inputStr;
public void setInputStr(String Str){
this.inputStr=Str.toUpperCase();
}
public String getInputStr(){
return this.inputStr;
}
public void Save(String path){
File file=new File(path);
if(file.exists()){
System.out.println("創建單個文件"+path+"失敗,目標文件已經存在");
}
if(path.endsWith((File.separator))){
System.out.println("創建單個文件"+path+"失敗,目標文件不能是目錄");
}
if(!file.getParentFile().exists()){
System.out.println("目標文件所在的目錄不存在,準備創建它!");
if(!file.getParentFile().mkdirs()){
System.out.println("創建目標文件所在的目錄失敗!");
}
}
try{
Printstream(file);
Filewriter(file);
Printwriter(file);
FileOutstream(file);
}catch(Exception e){
e.printStackTrace();
}
}
public void Printstream(File file){
try{
PrintStream ps =new PrintStream(new FileOutputStream(file));
ps.println(this.getInputStr());
}catch(FileNotFoundException e){
e.printStackTrace();
}
}
public void Filewriter(File file){
try{
FileWriter fw=new FileWriter(file.getAbsolutePath(),true);
BufferedWriter bw=new BufferedWriter(fw);
bw.write(this.getInputStr());
bw.close();
fw.close();
}catch(IOException e){
e.printStackTrace();
}
}
public void Printwriter(File file){
try{
PrintWriter pw=new PrintWriter(new FileWriter(file.getAbsolutePath()));
pw.println(this.getInputStr());
pw.close();
}catch(IOException e){
e.printStackTrace();
}
}
public void FileOutstream(File file){
try{
FileOutputStream fos=new FileOutputStream(file.getAbsolutePath());
fos.write(this.getInputStr().getBytes());
fos.close();
}catch(IOException e){
e.printStackTrace();
}
}
public static void main(String[] args){
Scanner in =new Scanner(System.in);
String Str=in.nextLine();
Test temp=new Test();
temp.setInputStr(Str);
temp.Save("D:\\temp\\test.txt");
}
}
Java 將字符串輸入文件中