问题
I am trying to Write several lines of commands in console in java Eclipse, and then save them as a .txt file. For example i have
do this
do not do that
at my console and i want to have the same thing as a .txt file.Now I can convert it to a file but not a .txt file and not the same readable shape. any help? I've been working on it for 3 days now :))
i think this is the closest i could get
FileInputStream fileInputStream=null;
File file = new File("C:\\Users\\Administrator\\Desktop\\a.txt");
byte[] bFile = new byte[(int) file.length()];
try {
//convert file into array of bytes
fileInputStream = new FileInputStream(file);
fileInputStream.read(bFile);
fileInputStream.close();
//convert array of bytes into file
FileOutputStream fileOuputStream =
new FileOutputStream("C:\\Users\\Administrator\\Desktop\\a.txt");
fileOuputStream.write(bFile);
fileOuputStream.close();
System.out.println("Done");
}catch(Exception e){
e.printStackTrace();
}
回答1:
Instead of using bytes, I would recommend using text streams, if you're writing text files. To write "Hello world" to a text file at "M:\outputfile.txt" for example:
import java.io.*;
public class FileIOExample {
public static void main(String[] args) {
PrintWriter out;
try {
out = new PrintWriter(new FileWriter("M:\\outputfile.txt"));
out.print("Hello ");
out.println("world");
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
回答2:
the line new byte[(int) file.length()]
is causing problem
as the initial length of a.txt
is practically zero
or non-existing
your code might fail to read any bytes.
instread i recommend,
Have a fixed buffer size to read content with a possible exit creiteria.
Read the char to a stream and define an exit creiteria like if chars
.equals()
exit etcfinally write bytes/chars to the file
Some example code for the approach mentioned:
BufferedReader br = null;
Reader r = new InputStreamReader(System.in);
br = new BufferedReader(r);
String str = null;
try {
do{
System.out.println("Enter Input, exit to quit.");
str = br.readLine();
System.out.println(str);
} while (!str.equalsIgnoreCase("exit"));
} catch (IOException e) {
e.printStackTrace();
}
来源:https://stackoverflow.com/questions/14723418/how-to-save-lines-of-console-input-as-a-txt-file