Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/368.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java——缓冲读取_Java - Fatal编程技术网

Java——缓冲读取

Java——缓冲读取,java,Java,我正在为自己编写一个程序,它显示了在文本文件中阅读的所有不同方式。我使用了FileWriter和BufferedWriter --------------------------------------------------------- - FileWriter fw = new FileWriter (file); - - BufferedWriter bw = new BufferedWriter (fw); - -

我正在为自己编写一个程序,它显示了在文本文件中阅读的所有不同方式。我使用了FileWriter和BufferedWriter

  ---------------------------------------------------------
  -        FileWriter fw = new FileWriter (file);         -
  -        BufferedWriter bw = new BufferedWriter (fw);   - 
  -        PrintWriter outFile = new PrintWriter (bw);    - 
  ---------------------------------------------------------
我这里的问题是为什么FileWriter变量需要包装在BufferedWriter中。我在代码中经常看到这一点,在某些情况下,比如整数包装的int。这在这里对我来说是有意义的,但是在BufferedWriter中包装FileWriter会获得什么好处呢

    **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);
                }
     }
导入java.io.BufferedReader;
导入java.io.BufferedWriter;
导入java.io.File;
导入java.io.FileInputStream;
导入java.io.FileNotFoundException;
导入java.io.FileReader;
导入java.io.FileWriter;
导入java.io.IOException;
导入java.nio.charset.charset;
导入java.nio.charset.StandardCharset;
导入java.nio.file.Files;
导入java.nio.file.Path;
导入java.nio.file.path;
导入java.util.ArrayList;
导入java.util.array;
导入java.util.List;
导入java.util.Locale;
导入java.util.Scanner;
公共类DDHExampleTextFileReader{
列表行=新的ArrayList();
最终静态字符串文件\u NAME=“G:testFile.txt”;
最终静态字符串输出\u文件\u NAME=“G:OUTPUT.txt”;
最终静态字符集编码=StandardCharsets.UTF_8;
私有静态final int DEFAULT_BUFFER_SIZE=1024*4;
公共DDHExampleTextFileReader(){
//零参数构造函数
}
私有void fileReadOne(){
String fileName=“G:testFile.txt”;//要打开的文件的名称。
String line=null;//这将一次引用一行
试一试{
//FileReader以默认编码读取文本文件。
//FileReader用于读取字符流。
//用于读取原始字节流,考虑使用FieldPixSt流。
FileReader FileReader=新的FileReader(文件名);
//始终将文件读取器包装在BufferedReader中。
BufferedReader BufferedReader=新的BufferedReader(文件阅读器);
而((line=bufferedReader.readLine())!=null){
系统输出打印项次(行);
}   
bufferedReader.close();//始终关闭文件。
}
捕获(FileNotFoundException ex){
System.out.println(
“无法打开文件”“+
文件名+“'”;
}
捕获(IOEX异常){
System.out.println(“读取文件“+”文件名“+”时出错”);
例如printStackTrace();
//或者我们可以这样做:
//例如printStackTrace();
}
}
私有void fileReadTwo(){
//要打开的文件的名称。
String fileName=“G:testFile.txt”;
试一试{
//使用此选项读取数据。
字节[]缓冲区=新字节[1000];
FileInputStream inputStream=
新文件输入流(文件名);
//读取用数据填充缓冲区并返回
//读取的字节数(当然是
//可能小于缓冲区大小,但
//它将永远不会更大)。
int-total=0;
int nRead=0;
而((nRead=inputStream.read(buffer))!=-1){
//转换为字符串以便我们可以显示它。
//你当然不想和我一起做这件事
//“真实”二进制文件。
System.out.println(新字符串(缓冲区));
总+=nRead;
}   
//始终关闭文件。
inputStream.close();
System.out.println(“读取”+总计+“字节”);
}
捕获(FileNotFoundException ex){
System.out.println(
“无法打开文件”“+
文件名+“'”;
}
捕获(IOEX异常){
System.out.println(
“读取文件“”时出错”
+文件名+“'”;
//或者我们可以这样做:
//例如printStackTrace();
}
}
私有void fileReadThree(){
字符串内容=null;
File File=new File(“G:testFile.txt”);//对于ex foo.txt
FileReader=null;
试一试{
reader=新文件读取器(文件);
char[]chars=new char[(int)file.length()];
读卡器,读卡器;
内容=新字符串(字符);
系统输出打印项次(内容);
}捕获(IOE异常){
e、 printStackTrace();
}最后{
试一试{
reader.close();
}捕获(IOE异常){
e、 printStackTrace();
}
}
}
私有void fileReadFour(){
文件f=新文件(“G:testFile.txt”);
字符串文本=”;
读取整数,N=1024*1024;
char[]buffer=新字符[N];
试一试{
FileReader fr=新的FileReader(f);
BufferedReader br=新的BufferedReader(fr);