- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我正在为自己开发一个程序,它展示了读取文本文件的所有不同方式。我用过 FileWriter 和 BufferedWriter。
我的问题是为什么 FileWriter 变量需要包装在 BufferedWriter 中。我在代码中经常看到这一点,在某些情况下,例如 int 包装在 Integer 中。这对我来说很有意义,但是将 FileWriter 包装在 BufferedWriter 中有什么好处。
**FileWriter fWriter = new FileWriter(fileName);
BufferedWriter bW = new BufferedWriter(fWriter);**
我在这个网站上找到了下面的代码,我通读了评论和答案,发现它有点帮助完整
我认为令人困惑的部分是文件有很多不同的缓冲读取。读取文件的最佳方式是什么以及为什么必须将它们包装在其他对象中。它可以方法支持吗?它会刷新缓冲区吗?它会提高速度吗? (可能不是)将文件包装在缓冲区中是否有一些很大的优势。
FileWriter fWriter = new FileWriter(fileName);
BufferedWriter bW = new BufferedWriter(fWriter);
在上面的代码中,fWriter 是用文件名创建的。然后 fWriter 变量被“包装”到 BufferedWriter bW 变量中。将 FileWriter 包装到 BufferedWriter 中的真正目的是什么。
---------------------------------------------------------
- FileWriter fw = new FileWriter (file); -
- BufferedWriter bw = new BufferedWriter (fw); -
- PrintWriter outFile = new PrintWriter (bw); -
---------------------------------------------------------
下面是我的完整文件程序。我真的只是对缓冲包装器有疑问,但我认为如果有人想要编译并运行它,我无论如何都会以这种方式发布它,那么他们真的应该不会遇到任何麻烦。
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Scanner;
public class DDHExampleTextFileReader {
List<String> lines = new ArrayList<String>();
final static String FILE_NAME = "G:testFile.txt";
final static String OUTPUT_FILE_NAME = "G:output.txt";
final static Charset ENCODING = StandardCharsets.UTF_8;
private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
public DDHExampleTextFileReader() {
//Zero argument constructor
}
private void fileReadOne() {
String fileName = "G:testFile.txt"; // The name of the file to open.
String line = null; // This will reference one line at a time
try {
// FileReader reads text files in the default encoding.
// FileReader is meant for reading streams of characters.
// For reading streams of raw bytes, consider using a FileInputStream.
FileReader fileReader = new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close(); // Always close files.
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println("Error reading file '" + fileName + "'");
ex.printStackTrace();
// Or we could just do this:
// ex.printStackTrace();
}
}
private void fileReadTwo() {
// The name of the file to open.
String fileName = "G:testFile.txt";
try {
// Use this for reading the data.
byte[] buffer = new byte[1000];
FileInputStream inputStream =
new FileInputStream(fileName);
// read fills buffer with data and returns
// the number of bytes read (which of course
// may be less than the buffer size, but
// it will never be more).
int total = 0;
int nRead = 0;
while((nRead = inputStream.read(buffer)) != -1) {
// Convert to String so we can display it.
// Of course you wouldn't want to do this with
// a 'real' binary file.
System.out.println(new String(buffer));
total += nRead;
}
// Always close files.
inputStream.close();
System.out.println("Read " + total + " bytes");
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
private void fileReadThree() {
String content = null;
File file = new File("G:testFile.txt"); //for ex foo.txt
FileReader reader = null;
try {
reader = new FileReader(file);
char[] chars = new char[(int) file.length()];
reader.read(chars);
content = new String(chars);
System.out.println(content);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void fileReadFour() {
File f = new File("G:testFile.txt");
String text = "";
int read, N = 1024 * 1024;
char[] buffer = new char[N];
try {
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
while(true) {
read = br.read(buffer, 0, N);
text += new String(buffer, 0, read);
if(read < N) {
break;
}
}
} catch(Exception ex) {
ex.printStackTrace();
}
System.out.println(text);
}
//Doesn't keep file formatting
private void fileReadfive() {
Scanner s = null;
try {
try {
s = new Scanner(new BufferedReader(new FileReader("G:testFile.txt")));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (s.hasNext()) {
System.out.println(s.next());
}
} finally {
if (s != null) {
s.close();
}
}
}
private void fileReadSumsTheFileOfNumbersScanner() {
Scanner s = null;
double sum = 0;
try {
try {
s = new Scanner(new BufferedReader(new FileReader("G:n.txt")));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
s.useLocale(Locale.US);
while (s.hasNext()) {
if (s.hasNextDouble()) {
sum += s.nextDouble();
} else {
s.next();
}
}
} finally {
s.close();
}
System.out.println(sum);
}
private void fileWriterOneTextFile() {
String fileName = "G:testTemp.txt";
try {
// Assume default encoding.
/*
Whether or not a file is available or may be created depends upon the underlying platform. Some platforms, in particular,
allow a file to be opened for writing by only one FileWriter (or other file-writing object) at a time. In such
situations the constructors in this class will fail if the file involved is already open.
FileWriter is meant for writing streams of characters. For writing streams of raw bytes, consider using a
FileOutputStream.
*/
FileWriter fWriter = new FileWriter(fileName);
// Always wrap FileWriter in BufferedWriter.
/*
The buffer size may be specified, or the default size may be accepted. The default is large enough for most purposes.
A newLine() method is provided, which uses the platform's own notion of line separator as defined by the system
property line.separator. Not all platforms use the newline character ('\n') to terminate lines. Calling this method
to terminate each output line is therefore preferred to writing a newline character directly.
In general, a Writer sends its output immediately to the underlying character or byte stream. Unless prompt output
is required, it is advisable to wrap a BufferedWriter around any Writer whose write() operations may be costly, such as
FileWriters and OutputStreamWriters. For example,
PrintWriter out
= new PrintWriter(new BufferedWriter(new FileWriter("foo.out")));
will buffer the PrintWriter's output to the file. Without buffering, each invocation of a print() method would cause
characters to be converted into bytes that would then be written immediately to the file, which can be very inefficient.
*/
BufferedWriter bW = new BufferedWriter(fWriter);
// Note that write() does not automatically
// append a newline character.
bW.write("This is a test string that will be written to the file!!!!");
bW.write("This more text that will be written to the file!!!!");
bW.newLine();
bW.write("After the newLine bufferedWriter method.");
bW.write(" A B C D E F G");
bW.newLine();
bW.write("Hauf");
bW.close();
} catch(IOException ex) {
System.out.println("Error writing to file '" + fileName + "'");
ex.printStackTrace();
}
}
List<String> readSmallTextFile(String aFileName) throws IOException {
Path path = Paths.get(aFileName);
return Files.readAllLines(path, ENCODING);
}
void writeSmallTextFile(List<String> aLines, String aFileName) throws IOException {
Path path = Paths.get(aFileName);
Files.write(path, aLines, ENCODING);
}
//For larger files
void readLargerTextFile(String aFileName) throws IOException {
Path path = Paths.get(aFileName);
try (Scanner scanner = new Scanner(path, ENCODING.name())){
while (scanner.hasNextLine()){
//process each line in some way
log(scanner.nextLine());
}
}
}
void readLargerTextFileAlternate(String aFileName) throws IOException {
Path path = Paths.get(aFileName);
try (BufferedReader reader = Files.newBufferedReader(path, ENCODING)){
String line = null;
while ((line = reader.readLine()) != null) {
//process each line in some way
log(line);
}
}
}
void writeLargerTextFile(String aFileName, List<String> aLines) throws IOException {
Path path = Paths.get(aFileName);
try (BufferedWriter writer = Files.newBufferedWriter(path, ENCODING)){
for(String line : aLines){
writer.write(line);
writer.newLine();
}
}
}
private static void log(Object aMsg){
System.out.println(String.valueOf(aMsg));
}
public static void main(String[] args) throws IOException {
DDHExampleTextFileReader doug = new DDHExampleTextFileReader();
List<String> lines = doug.readSmallTextFile(FILE_NAME);
//doug.fileReadOne();
//doug.fileReadTwo();
//doug.fileReadThree();
//doug.fileReadFour();
//doug.fileReadfive();
//doug.fileReadSumsTheFileOfNumbersScanner();
doug.fileWriterOneTextFile();
log(lines);
lines.add("This is a line added in code.");
doug.writeSmallTextFile(lines, FILE_NAME);
doug.readLargerTextFile(FILE_NAME);
lines = Arrays.asList("Down to the Waterline", "Water of Love");
doug.writeLargerTextFile(OUTPUT_FILE_NAME, lines);
System.out.println(String.valueOf("\n\n\n-----End of Main Method!!!------"));
}
}
/*
public static void copy(Reader input, OutputStream output, String encoding)
throws IOException {
if (encoding == null) {
copy(input, output);
} else {
OutputStreamWriter out = new OutputStreamWriter(output, encoding);
copy(input, out);
// XXX Unless anyone is planning on rewriting OutputStreamWriter,
// we have to flush here.
out.flush();
}
}
public static void copy(Reader input, OutputStream output)
throws IOException {
OutputStreamWriter out = new OutputStreamWriter(output);
copy(input, out);
// XXX Unless anyone is planning on rewriting OutputStreamWriter, we
// have to flush here.
out.flush();
}
public static int copy(Reader input, Writer output) throws IOException {
// long count = copyLarge(input, output);
//copy large
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
long count = 0;
int n = 0;
while (-1 != (n = input.read())) {
output.write(0);
count += n;
}
//end copy large
if (count > Integer.MAX_VALUE) {
return -1;
}
return (int) count;
}
public static long copyLarge(InputStream i, OutputStream o) throws IOException {
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
long count = 0;
int n = 0;
while (-1 != (n = i.read(buffer))) {
o.write(buffer, 0, n);
count += n;
}
return count;
}
public static String toString(InputStream input) throws IOException {
StringWriter sw = new StringWriter();
copy(input, sw);
return sw.toString();
}
public static void copy(InputStream input, Writer output) throws IOException {
InputStreamReader in = new InputStreamReader(input);
copy(in, output);
}
public static void copy(InputStream input, Writer output, String encoding) throws IOException {
if (encoding == null) {
copy(input, output);
} else {
InputStreamReader in = new InputStreamReader(input, encoding);
copy(in, output);
}
}
最佳答案
My question here is why does the FileWriter variable need to be wrapped in a BufferedWriter.
它不是必须 - 但如果这样做,您可能会获得更好的性能,从而避免经常访问磁盘。
此外,您正在使用 BufferedWriter.newLine
,未为 FileWriter
定义- 不过,手动编写新行会很容易。
我建议您使用 FileOutputStream
包裹在 OutputStreamWriter
中, 而不是使用 FileWriter
直接 - 这样您就可以指定应该使用的编码,而不仅仅是使用平台默认编码。
我还建议避免 PrintWriter
因为它会吞下异常 - IMO,这不是一个好主意。
关于Java——缓冲读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20271873/
我正在编写一个具有以下签名的 Java 方法。 void Logger(Method method, Object[] args); 如果一个方法(例如 ABC() )调用此方法 Logger,它应该
我是 Java 新手。 我的问题是我的 Java 程序找不到我试图用作的图像文件一个 JButton。 (目前这段代码什么也没做,因为我只是得到了想要的外观第一的)。这是我的主课 代码: packag
好的,今天我在接受采访,我已经编写 Java 代码多年了。采访中说“Java 垃圾收集是一个棘手的问题,我有几个 friend 一直在努力弄清楚。你在这方面做得怎么样?”。她是想骗我吗?还是我的一生都
我的 friend 给了我一个谜语让我解开。它是这样的: There are 100 people. Each one of them, in his turn, does the following
如果我将使用 Java 5 代码的应用程序编译成字节码,生成的 .class 文件是否能够在 Java 1.4 下运行? 如果后者可以工作并且我正在尝试在我的 Java 1.4 应用程序中使用 Jav
有关于why Java doesn't support unsigned types的问题以及一些关于处理无符号类型的问题。我做了一些搜索,似乎 Scala 也不支持无符号数据类型。限制是Java和S
我只是想知道在一个 java 版本中生成的字节码是否可以在其他 java 版本上运行 最佳答案 通常,字节码无需修改即可在 较新 版本的 Java 上运行。它不会在旧版本上运行,除非您使用特殊参数 (
我有一个关于在命令提示符下执行 java 程序的基本问题。 在某些机器上我们需要指定 -cp 。 (类路径)同时执行java程序 (test为java文件名与.class文件存在于同一目录下) jav
我已经阅读 StackOverflow 有一段时间了,现在我才鼓起勇气提出问题。我今年 20 岁,目前在我的家乡(罗马尼亚克卢日-纳波卡)就读 IT 大学。足以介绍:D。 基本上,我有一家提供簿记应用
我有 public JSONObject parseXML(String xml) { JSONObject jsonObject = XML.toJSONObject(xml); r
我已经在 Java 中实现了带有动态类型的简单解释语言。不幸的是我遇到了以下问题。测试时如下代码: def main() { def ks = Map[[1, 2]].keySet()
一直提示输入 1 到 10 的数字 - 结果应将 st、rd、th 和 nd 添加到数字中。编写一个程序,提示用户输入 1 到 10 之间的任意整数,然后以序数形式显示该整数并附加后缀。 public
我有这个 DownloadFile.java 并按预期下载该文件: import java.io.*; import java.net.URL; public class DownloadFile {
我想在 GUI 上添加延迟。我放置了 2 个 for 循环,然后重新绘制了一个标签,但这 2 个 for 循环一个接一个地执行,并且标签被重新绘制到最后一个。 我能做什么? for(int i=0;
我正在对对象 Student 的列表项进行一些测试,但是我更喜欢在 java 类对象中创建硬编码列表,然后从那里提取数据,而不是连接到数据库并在结果集中选择记录。然而,自从我这样做以来已经很长时间了,
我知道对象创建分为三个部分: 声明 实例化 初始化 classA{} classB extends classA{} classA obj = new classB(1,1); 实例化 它必须使用
我有兴趣使用 GPRS 构建车辆跟踪系统。但是,我有一些问题要问以前做过此操作的人: GPRS 是最好的技术吗?人们意识到任何问题吗? 我计划使用 Java/Java EE - 有更好的技术吗? 如果
我可以通过递归方法反转数组,例如:数组={1,2,3,4,5} 数组结果={5,4,3,2,1}但我的结果是相同的数组,我不知道为什么,请帮助我。 public class Recursion { p
有这样的标准方式吗? 包括 Java源代码-测试代码- Ant 或 Maven联合单元持续集成(可能是巡航控制)ClearCase 版本控制工具部署到应用服务器 最后我希望有一个自动构建和集成环境。
我什至不知道这是否可能,我非常怀疑它是否可能,但如果可以,您能告诉我怎么做吗?我只是想知道如何从打印机打印一些文本。 有什么想法吗? 最佳答案 这里有更简单的事情。 import javax.swin
我是一名优秀的程序员,十分优秀!