java 如何从输入流重新打开文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12347823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 08:30:53  来源:igfitidea点击:

How to reopen a file from a input stream

javafile-io

提问by user179516

I want to re-open a file. I have a file in Input stream. I have tried using Scanner and using BufferedReader. But I am unable to open the file again after it is closed using close() method. Please help how to open a file again. I have written the below code:

我想重新打开一个文件。我在输入流中有一个文件。我曾尝试使用 Scanner 和 BufferedReader。但是在使用 close() 方法关闭文件后,我无法再次打开该文件。请帮助如何再次打开文件。我写了下面的代码:

InputStream filename = getAttachstream();

        int rows =0 ;

        BufferedReader br= new BufferedReader(new InputStreamReader(filename));
        String strLine = "";
          try {
            while( (strLine = br.readLine()) != null) {
                rows++;
              }
            //br.reset();
            br.close();
            //br.reset();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
if(rows>0){
            InputStream filename1 = getAttachstream();
            Scanner inputStream1 = new Scanner(filename1);
                for (int rowIncr = 1; inputStream1.hasNext(); rowIncr++) {

                String data;
                try {
                    data = br.readLine();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                String [] values = data.split(",");
                String curRowPartNumber = values[0];
                String curRowQuantity =   values[1];
                if(rowIncr == 1)
                {
                    if((values[0]==null || values[0].trim().length()<=0)
                            || (values[1]==null || values[1].trim().length()<=0)
                            || (values[2] != "") || !"Part Number".equalsIgnoreCase(values[0].trim())
                            || !"Quantity".equalsIgnoreCase(values[1].trim())){
                        System.out.println("Invalid Excel sheet data");
                        throw new ECApplicationException(ECMessage._ERR_CMD_INVALID_DATAFORMAT, CLASSNAME,methodName);
                    }

                }

回答by Peter Lawrey

Once a stream, reader, writer, socket or any other resource has closed, you can't open it again.

一旦流、读取器、写入器、套接字或任何其他资源关闭,您将无法再次打开它。

If you want to read a file more than once, you need to have its file name.

如果你想多次读取一个文件,你需要有它的文件名。

回答by SJuan76

I assume you mean to reopen the InputStream you get from getAttachstream(even it is not shown nowhere that it comes from a file).

我假设您的意思是重新打开您从中获得的 InputStream getAttachstream(即使它没有在任何地方显示它来自文件)。

The only option would be for getAttachstreamto return a class that implement such method. Keep in mind that even FileInputStreamdoes not offer such option. And, even if you find the concrete class and it happens to have such a method, as the definition of the method returns an InputStreamyou can't be sure that it will always return that same class (or even that in all circunstance that will be the class returned).

唯一的选择是getAttachstream返回一个实现这种方法的类。请记住,即使FileInputStream不提供此类选项。而且,即使你找到了具体的类并且它碰巧有这样的方法,因为方法的定义返回一个InputStream你不能确定它总是会返回同一个类(甚至在所有情况下都会返回)班级回来了)。

The only option would be using the original inputStream and write it into a temporary file or a ByteArrayOutputStream(if the file/s are small enough to not use too much memory), so you can access the data several times.

唯一的选择是使用原始 inputStream 并将其写入临时文件或 a ByteArrayOutputStream(如果文件/s 足够小以不使用太多内存),因此您可以多次访问数据。

回答by Amit Deshpande

You can use scanner to count rows Scanner.hasNextLine()

您可以使用扫描仪来计算行数Scanner.hasNextLine()

Returns true if there is another line in the input of this scanner. This method may block while waiting for input. The scanner does not advance past any input.

如果此扫描仪的输入中有另一行,则返回 true。此方法可能会在等待输入时阻塞。扫描仪不会通过任何输入。

    File file = new File("C:/test.txt");
    File file1 = new File("C:/test1.txt");

    Scanner scanner;
    try {
        FileInputStream fileInputStream = new FileInputStream(file);
        FileInputStream fileInputStream1 = new FileInputStream(file1);
        scanner = new Scanner(fileInputStream);
        int count = 0;
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            count++;
        }
        scanner.close();
        System.out.println("File 1 Count:" + count);
        scanner = new Scanner(fileInputStream1);
        count = 0;
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            count++;
        }
        System.out.println("File 2 Count:" + count);
        scanner.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }