我需要建立一个系统,用于将客户信息和所有报价存储到外部文件,以及输入更多客户,列出客户,以及相同的报价。除此之外,我需要将所有报价/客户链接到ID。我基本上需要在java中做SQL。但是,我真的需要帮助我的输入和输出系统,并将所有信息写入数组。我有两个主要的代码,但它们效率很低,我需要一些建议,改进或完全不同的系统。 从文件代码输入:
import java.io.*; //import classes
import java.util.ArrayList;
import java.util.Iterator;
public class MyTextReader{
public static void main(String[] args){
String myDirectory = System.getProperty("user.dir");
String fullDirectory = myDirectory + "\\myText.txt";
String input_line = null;
ArrayList<String> textItems = new ArrayList<String>(); //create array list
try{
BufferedReader re = new BufferedReader(new FileReader(fullDirectory));
while((input_line = re.readLine()) != null){
textItems.add(input_line); //add item to array list
}
}catch(Exception ex){
System.out.println("Error: " + ex);
}
Iterator myIteration = textItems.iterator(); //use Iterator to cycle list
while(myIteration.hasNext()){ //while items exist
System.out.println(myIteration.next()); //print item to command-line
}
}
}
输出到文件
import java.io.FileWriter; //import classes
import java.io.PrintWriter;
public class MyTextWriter{
public static void main(String[] args){
FileWriter writeObj; //declare variables (uninstantiated)
PrintWriter printObj;
String myText = "Hello Text file";
try{ //risky behaviour – catch any errors
writeObj = new FileWriter("C:\\Documents\\myText.txt" , true);
printObj = new PrintWriter(writeObj);//create both objects
printObj.println(myText); //print to file
printObj.close(); //close stream
}catch(Exception ex){
System.out.println("Error: " + ex);
}
}
}
答案 0 :(得分:1)
用于从文件中读取文本
FileReader fr = new FileReader("YourFile.txt");
BufferedReader br = new BufferedReader(fr);
String s="";
s=br.readLine();
System.out.println(s);
将文字写入文件
PrintWriter writeText = new PrintWriter("YourFile.txt", "UTF-8");
writeText.println("The first line");
writeText.println("The second line");
writeText.close();