【问题标题】:take in different files接收不同的文件
【发布时间】:2011-06-11 08:04:03
【问题描述】:

您好,我正在编写一个程序,它接收一个文本文件并通过它,如果它发现消息 #GetFile "filename.txt" 去获取它并将它存储在与第一个文本文件相同的数组列表中,但我不是能够思考问题,因为如果一个文件调用另一个文件,该文件又调用另一个文件,并且该文件可能能够调用另一个文件。而且我想知道是否可以一遍又一遍地调用包含扫描仪类的方法。

 This is file one 
 #GetFile "fileSecond.txt"

 ----------
 this is file two
 #GetFile "fileThird.txt" 
 ----------
 this is text file three
 #GetFile "fileOne.txt"

这是不同的文本文件有它的方式 ---

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

public class Project3
{
  public static void main(String[] args) 
  {
    ArrayList<String> text = new ArrayList<String>();
    File dictionaryFile = null; // set default value
    File dictionaryFileTwo = null;
    Scanner inputFile = null; // set default value
    Scanner inputFileTwo = null;
    // use a try-catch block to handle situations when the file is not present
    keyboard = new Scanner(System.in);
    // fileName = keyboard.next();
    String fileName = "test1.txt";
    try {
      dictionaryFile = new File(fileName); // declare the file
      inputFile = new Scanner(dictionaryFile);
    } catch (Exception e) {
      // if File object creation failed (such as when file is not there)
      // then this code gets executed.
      // print the directory where this program expects to find dictionary
      System.out.println(System.getProperty("user.dir"));
      // ensure file exists and is in the correct directory
      if (!dictionaryFile.exists()) {
        System.out.println("*** Error *** \n"
            + "Your text file has the wrong name or is "
            + "in the wrong directory.  \n"
            + "Aborting program...\n\n");
        System.exit(-1); // Terminate the program
      }
    }// end catch

    // while there are words in the input file, add them to the dictionary
    while (inputFile.hasNext()) {
      if(inputFile.next().startsWith("#GetFile")){
        String filing = inputFile.next();
        System.out.println("HEY THIS IS THE FILE THAT I FOUND "+ filing);
        String fileNameSecond = filing;
        try {
          dictionaryFileTwo = new File(filing); // declare the file
          inputFile = new Scanner(dictionaryFile);
        }catch (Exception e) {
          // if File object creation failed (such as when file is not there)
          // then this code gets executed.
          // print the directory where this program expects to find dictionary
          System.out.println(System.getProperty("user.dir"));
          // ensure file exists and is in the correct directory
          if (!dictionaryFile.exists()) {
            System.out.println("*** Error *** \n"
                + "Your text file has the wrong name or is "
                + "in the wrong directory.  \n"
                + "Aborting program...\n\n");
            System.exit(-1); // Terminate the program
          }
        }// end catch
      } else {
        text.add(inputFile.nextLine());
      }
    }
    for(int i =0; i < text.size(); i++){
      System.out.println(text.get(i));
    }
  }
}

【问题讨论】:

  • 使用递归似乎很自然。你有一个 loadFile(filename1) 它可以调用 loadFile(filename2)
  • 它不会通过arraylist,因为我想将每个文本文件存储在它被调用的地方。
  • 所以基本上,你想实现 C 预处理器#include 功能......对吗?
  • 是的,这正是我想要完成但使用 GetFile
  • @corlettk 但是我很难想象它是如何工作的。

标签: java methods java.util.scanner


【解决方案1】:

基本算法是:

open the output-file

ExpandIncudes(input-file, output-file) {
  open input-file
  while (read line from input)
    if (line is-a #include) then
      ExpandIncudes(input-file)
    else
      write line to output-file
    endif
  next line
}

不,我认为你不能一直重复使用同一个扫描仪来读取不同的文件。

干杯。基思。

【讨论】:

  • 所以我会有两个扫描仪类?
  • 您将拥有一个 Scanner 类和一个扫描仪变量,但每次调用该方法都有自己的副本,您将拥有与同时打开的文件一样多的副本。
【解决方案2】:

您的问题有点混乱,但您似乎需要研究如何在这里使用一些递归。

您只需要一个方法,在找到“#GetFile”指令后,该方法将获取文件名以获取并使用该名称再次调用该方法。

public void parseFile(String filename) {
    //readline while not end of file...

    //is line a #GetFile directive?
        //parseFile(newFilename)  
}

...或类似的东西

【讨论】:

    【解决方案3】:

    西伯加图,

    我假设你的作业已经交了,所以把“答案”交给你是“安全的”。

    我会这样做:

    package forums;
    
    import java.io.File;
    import java.io.FileReader;
    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    
    public class HashInclude
    {
      private static final String[] INCLUDE_PATH = 
        System.getenv("INCLUDE_PATH").split(File.pathSeparator);
    
      public static void main(String... args) {
        try {
          for ( String filename : filenames ) {
            hashInclude(filename);
          }
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    
      public static void hashInclude(String filename)
        throws FileNotFoundException, IOException
      {
        BufferedReader reader = new BufferedReader(new FileReader(filename));
        try {
          String line = null;
          int lineCount = 0;
          while ( (line=reader.readLine()) != null ) {
            ++lineCount;
            if ( line.startsWith("#include ") ) {
              String targetFilename = line.replaceFirst("^#include[ \t]*", "").trim();
              if ( !targetFilename.matches("^[<\"][A-z0-9_]+\\.h[\">]$") )
                // not a <valid.h> or a "valid.h"
                throw new IncludeException(targetFilename, lineCount, filename);
              // <valid.h> --> valid.h
              targetFilename = targetFilename.substring(1, targetFilename.length()-1);
              // search directories in the INCLUDE_PATH for targetFilename
              for ( String dir : INCLUDE_PATH ) {
                File targetFile = new File(dir, targetFilename); // c:/path/to/valid.h
                if ( targetFile.exists() ) {
                  hashInclude( targetFile.getAbsolutePath() ); // <<-- recursive call
                  return;
                }
              } // next dir
              throw new FileNotFoundException("File " + targetFilename 
                + " not found in INCLUDE_PATH="+ System.getenv("INCLUDE_PATH"));
            } else {
              System.out.println(line);
            }
          } // next line
        } finally {
          reader.close();
        }
      }
    
    }
    
    class IncludeException extends RuntimeException {
      private static final long serialVersionUID = 0L;
      public IncludeException(String targetFilename, int lineCount, String filename) {
        super("Invalid #include: " + targetFilename + " at " + lineCount + " " + filename);
      }
    }
    

    我认为上述是解决问题的“合理优雅”的解决方案......即使我自己也这么说;-)

    请注意,hashInclude 方法会递归调用自身...递归自然会遵循“任意树结构”...即,当您编写软件时,其精确结构是未知的...和因此,“递归”是许多程序员想到“树”这个词时首先想到的东西。

    请注意,上面的代码实现了 C 预处理器#include 机制的极大简化版本...但可以(相当容易地)扩展为“适当的预处理器”...甚至(递归地)扩展#定义。

    干杯。基思。

    【讨论】:

    • 谢谢伙计,在我开始深入阅读它并开始阅读我的头顶结构和代码之后,我已经放弃了。但这看起来很有希望并且可以理解,谢谢!
    猜你喜欢
    • 2021-03-28
    • 2012-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-22
    • 1970-01-01
    • 2012-04-18
    • 1970-01-01
    相关资源
    最近更新 更多