zoukankan      html  css  js  c++  java
  • JAVA读取TXT文本中的数据

    现在在Demo.txt中存在数据:

    ABC

    需要将ABC从文本文件中读取出来

    代码片:

    import java.io.*;
    
    class  FileReaderDemo
    {
        public static void main(String[] args) throws IOException
        {
            //创建一个文件读取流对象,和指定名称的文件相关联。
            //要保证该文件是已经存在的,如果不存在,会发生异常FileNotFoundException
            FileReader fr = new FileReader("Demo.txt");
    
            //调用读取流对象的read方法。
            //read():一次读一个字符。而且会自动往下读。
            /*===========================一般思路==========================*/
            /*
            //最初思路
            int ch1 = fr.read();
            System.out.println("ch="+(char)ch1);
            
            int ch2 = fr.read();
            System.out.println("ch="+(char)ch2);
            
            int ch3 = fr.read();
            System.out.println("ch="+(char)ch3);
            //取出结束标识
            int ch4 = fr.read();
            System.out.println("ch="+ch4);
            */
            /*=================思路改进===================================*/
            /*
            while(true)
            {
                int ch = fr.read();
                if(ch==-1)
                    break;
                System.out.println("ch="+(char)ch);
            }
            */
            /*==============================思路优化=====================*/
            
            int ch = 0;
    
            while((ch=fr.read())!=-1)
            {
                System.out.println("ch="+(char)ch);
            }
            
            fr.close();
    
    
        }
    }

    通过一般思路可以读出结束标志为-1

    下面是一般思路运行结果:

  • 相关阅读:
    [NOI Online 2021 提高组] 愤怒的小 N
    CF1474F 1 2 3 4 ...
    CF1466H Finding satisfactory solutions
    CF1336F Journey
    [PKUSC2021]代金券
    如何科学地设计对拍随机种子
    CF1168E Xor Permutations
    「JOISC 2019 Day2」两种运输
    springboot json参数
    springboot整合webserver应用
  • 原文地址:https://www.cnblogs.com/OliverQin/p/5042654.html
Copyright © 2011-2022 走看看