如何在Java中从文本文件中打印多行?

时间:2016-01-16 21:14:28

标签: java arraylist io

我有一个包含三行代码的文本文件。 也就是说,

您好。 请问有什么可以帮你? 我今天能为你做些什么?

我尝试打印第一行并且它有效。现在我想在控制台中打印其余的行,但它只显示第一行4次。

您好。 你好。 你好。 你好。

以下是我尝试运行的代码,该文件位于根文件夹中。

public class Test
{

    public static void main(String[] args)
    {
        int counter = 0;
        /*open the file */
        BufferedReader reader = null;

        String greeting = null;
        int rand;
        File file = new File("Greetings.txt");

        try
        {
            reader = new BufferedReader(new FileReader(file));

            /*read the file*/
            String greetingPicker = null;

            /*single greeting*/
            /*greeting = greetingPicker;*/
            List<String> listOfGreetings = new ArrayList<String>();
            while ((greetingPicker = reader.readLine()) != null)
            {
                listOfGreetings.add(greetingPicker);
            }
            reader.close();

            rand = (int) Math.random() * (listOfGreetings.size()) + 1;
            greeting = listOfGreetings.get(rand - 1);

            for (int i = 0; i < listOfGreetings.size(); i++)
            {
                System.out.println(listOfGreetings.get(counter));
            }
        } catch (Exception e)
        {
            System.out.println("File cannot be found!!");
        }

    }

}

6 个答案:

答案 0 :(得分:4)

您获得了错误索引的值:您在循环中错误地使用了position: relative而不是top。改变这个

counter

到此:

i

顺便说一下,您正在使用for(int i=0; i < listOfGreetings.size(); i++){ System.out.println(listOfGreetings.get(counter)); } ,它会立即转换为for(int i=0; i < listOfGreetings.size(); i++){ System.out.println(listOfGreetings.get(i)); } ,因为您忘记添加正确的括号,因此请更改此

Math.random()

到此:

int

答案 1 :(得分:2)

你不需要你的柜台,使用我! ;)

for(int i=0; i < listOfGreetings.size();i++){
     System.out.println(listOfGreetings.get(i));
}

答案 2 :(得分:2)

只需更改

System.out.println(listOfGreetings.get(counter));

通过

System.out.println(listOfGreetings.get(i));

你忘了换柜台了。

答案 3 :(得分:1)

你不需要使用计数器,最后就像这样:

    for(int i=0; i < listOfGreetings.size();i++){

        System.out.println(listOfGreetings.get(i));

    }
    reader.close();

答案 4 :(得分:1)

此处的“计数器”变量未递增:

function Test-PipelineStuff
{
    [cmdletbinding()]
    Param(
        [Parameter(ValueFromPipeLine=$true)][int]$Foo,
        [Parameter(ValueFromPipeLine=$true)][int]$MaxMins
    )

    begin { 
        "THE START" 
        $StartTime = Get-Date
        $StopTime = (get-date).AddMinutes($MaxMins)
        "Stop time is: $StopTime"

        # Embedded cleanup function.
        function clean-up {
          "THE END"
        }

    } 

    process 
    {  
        $currTime = Get-Date
        if( $currTime -lt $StopTime ){
            "Processing $Foo"            
        }
        else {
            # Call the cleanup function just before stopping the pipeline.
            clean-up
            continue;
        }
    }

    end { 
      # Normal termination: call the cleanup function.
      clean-up
    }
}

您应该将其更改为“i”:

for(int i=0; i < listOfGreetings.size();i++){

     System.out.println(listOfGreetings.get(counter));

}

答案 5 :(得分:0)

尝试使用下面的块。它更简单,效果更好。

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;


public class FileReader{

   public static void main(String[] args){

      //define file path
      String stringFileToRead = "Greetings.txt";

      //the file
      File stringFile = new File(stringFileToRead);

      //Scanner object to take input from  the file
      Scanner fileToRead = null;

      try{
         //Read the file
         fileToRead = new Scanner(stringFile);

      }
      //catch exception
      catch (Exception e){
         System.out.println("Unable to open file.");  
         System.exit(0);
      }

      //print the content of the file 
      System.out.println("The file contains the following contents:\n");
      int lineNum = 1;
      while(fileToRead.hasNextLine()){
         String line = fileToRead.nextLine();
         System.out.println("Line "+lineNum+": "+line);
         lineNum++;
      }

   }

}
相关问题