2013-04-11 157 views
1

我试图用扫描仪类读取名为“test.txt”的文本文件。在txt文件中,它只是一个像这样的句子:“这是一个txt文件”。这句话是我想写出来的。但是,当我使用以下命令时,我写出的所有文本都是txt文件的名称:java UDPClient test.txt localhost。使用扫描仪类读取文件

任何人都可以在代码中看到错误的东西,以便我可以正确地使用它吗?我有两个可能的代码。

Import java.net.*; 
Import java.io.*; 
Import java.util.*; 

public class Test_scanner { 

    public String readFile(String fileName) throws IOException { 

     File file = new File("test.txt"); 
     StringBuilder fileContents = new StringBuilder((int)file.length()); 
     Scanner s = new Scanner(file); 
     String lineSeparator = System.getProperty("line.separator"); 

    try { 
     while (s.hasNextLine()) { 
      fileContents.append(s.nextLine() + lineSeparator); 
     } 
      return fileContents.toString(); 
     } finally { 
      s.close(); 
      } 
    } 
} 

我也有这样的代码:在你的import语句

import java.net.*; 
import java.io.*; 
import java.util.*; 

public class Test_scanner { 

    public static void readFile(String fileName) { 
     try { 
      File file = new File(fileName); 
      Scanner scanner = new Scanner(file); 
      while (scanner.hasNextLine()) { 
        System.out.println(scanner.nextLine()); 
      } 
        scanner.close(); 
      } catch (FileNotFoundException e) { 
        e.printStackTrace(); 
      } 
    } 
+0

你的代码的第二块正常工作对我来说,它绝对是打印文件内容,而不是文件名。但是,我会将'scanner.close()'移到'finally'块中。 – Quetzalcoatl 2013-04-11 15:28:42

回答

0

“导入”不应该大写所以你的代码的第二块有它正确。我没有看到任何代码中的main()方法;你需要一个main()方法来运行你的程序。假设你正在使用的命令行输入文件名,你可以使用这样的事情:

import.java.io.*; 
import.java.util.*; 

public class TestScanner{ 

    public static void main(String[] args) { 
     String sFileName = ""; 
     //checks if user enters a file name 
     if(args.length == 0) { 
     System.out.println("Please enter a file name in command line."); 
     //terminates program 
     System.exit(0); 
     } 
     else { 
     sFileName = args[0]; 
     } 

     File myFile = new File(sFileName); 
     //scanner object which reads from file 
     Scanner fileReader = null; 

     try { 
     //links scanner object to file. 
     fileReader = new Scanner(myFile); 
     } 
     catch (FileNotFoundException fnf) { 
     System.out.println("ERROR: File not found for " + sFileName); 
     //terminates program 
     System.exit(1); 
     } 

     System.out.println("Reading from file: " + sFileName + "\n"); 

     //fileReader reads each line from file. 
     while(fileReader.hasNextLine()) { 
     //stores each line from file trimmed 
     System.out.println(fileReader.nextLine()); 
     } 
    }//end main() method 
}//end TestScanner class