【问题标题】:read a file in an array java读取数组java中的文件
【发布时间】:2013-12-09 21:18:14
【问题描述】:

这里我的 IO 有问题。字符串 ext[] 仅读取 txt 文件中的最后一个条目,在这种情况下仅读取 jpg。 我想阅读所有内容,但它只阅读最后我必须将此代码保留在构造函数中 请指出错误 提前致谢

    /////Text file format 
      txt
      png
      jpg

  ///// file reading code

 String  line;
//// constructor 
  public MainFrame(){
    initComponents();
    fileChooser=new JFileChooser();
  try {
    Scanner in = new Scanner(new FileReader("ext.txt"));
     while (in.hasNextLine()) {
          line = in.nextLine(); 
        } System.out.println(line);
           String ext[] = line.split("\\n"); /// can't read all the strings from file.

     FileNameExtensionFilter filter = new FileNameExtensionFilter("TEXT FILES",ext); 
    fileChooser.setFileFilter(filter);} 
  catch(IOException io){

  }
  }

【问题讨论】:

  • 检查你的括号.....
  • 你的右花括号应该在line.split("\\n");之后
  • 不,我有字符串越权和变量范围的问题

标签: java string io


【解决方案1】:

你的问题是String ext[]

每次循环时都会覆盖变量ext[]。我认为你应该这样做:

try {
ArrayList<String> ext = new ArrayList<String>();
Scanner in = new Scanner(new FileReader("ext.txt"));
 while (in.hasNextLine()) {
      line = in.nextLine(); 
    } System.out.println(line);
       ext.append(line.split("\\n")); 

你可能需要做一些语法工作,因为我有一段时间没有在 java 中工作过,但我认为这是对的

【讨论】:

  • 我只需要字符串 var,因为 FIleNamefilter 方法只支持 String var。
  • 谢谢你的帮助但是我是通过简单的字符串连接函数完成的。 ////////////////// while (in.hasNextLine()) { line = in.nextLine(); line2= line2 += line+"\n";
  • @user3078848 啊,好吧,您不想将字符串放入数组而是一个长字符串?
【解决方案2】:

在 java 中逐行读取文件通常使用 BufferedReader 完成。所以你也可以处理异常并且你总是在阅读后关闭文件。

这是一个例子,但我强烈建议您阅读有关使用文件的更多信息。一个很好的开始是 oracle 文档 (http://docs.oracle.com/javase/tutorial/essential/io/file.html)

//a collection that stores the lines
List<String> lines = new ArrayList<String>()
BufferedReader buf = null;
try{
    buf = new BufferedReader(new FileReader(file));
    String line = null;

    while((line = buf.readLine()) != null){
        lines.add(line);
    }
//if something goes wrong   
catch(IOException ex){
    ex.printStackTrace();
}
finally{
    //closing the buffer, so that the file isnt locked anymore
    if(buf != null)
       buf.close();

} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多