Java/File Input Output/PrintStream — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 06:02, 1 июня 2010
Append string to a text file
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;
public class Main {
public static void main(String[] argv) {
append(new File("c:\\a.txt"), "value");
}
public static void append(File aFile, String content) {
try {
PrintStream p = new PrintStream(new BufferedOutputStream(new FileOutputStream(aFile, true)));
p.println(content);
p.close();
} catch (Exception e) {
e.printStackTrace();
System.err.println(aFile);
}
}
}
Create print stream for error logger
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
public class Main {
public static void main(String[] argv) throws Exception {
try {
} catch (Exception e) {
e.printStackTrace(getErrorLoggerPrintStream());
}
}
public static PrintStream getErrorLoggerPrintStream() {
try {
PrintStream s = new PrintStream(new FileOutputStream(new File("c:\\log.txt"), true));
return s;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
Save string value to a file
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;
public class Main {
public static void main(String[] argv) {
saveFile("c:\\a.txt", "value");
}
public static void saveFile(final String fileName, final String str) {
try {
File f = new File(fileName);
if (new File(f.getParent()).exists() == false) {
f.getParentFile().mkdirs();
}
f.createNewFile();
PrintStream p = new PrintStream(new FileOutputStream(f, false));
p.println(str);
p.close();
} catch (Exception e) {
e.printStackTrace();
System.err.println(fileName);
}
}
}