【问题标题】:Some correctly formatted text files not working for conversion to KML files某些格式正确的文本文件无法转换为 KML 文件
【发布时间】:2018-07-25 02:50:48
【问题描述】:

我目前正在尝试完成一个程序,它会提示用户输入数据文件名,然后我的程序将其转换为 KML(Google 地球文件)。问题是某些文件即使格式正确也不会转换为 KML。正确的格式是文本文件每行有两个数字,用空格分隔。

    import java.io.*;
    import java.util.Scanner;
    public class H8_Ruby{
    public static void main(String [] args){
    Scanner input = new Scanner(System.in);
    System.out.println("Enter file name: "); 
    String fileName = input.nextLine();
    Scanner inFile;
    try{
     inFile = new Scanner(new File(fileName));
     System.out.println("File found: " + fileName);
     try{
        PrintStream outFile = new PrintStream(new File("KMLFile.txt"));
        topPortion(outFile);
        int i = 0;
        while (inFile.hasNextLine()){
           i++;
           String line = inFile.nextLine();
           String[] arr = line.split(" ");
           outFile.println(" <Placemark>");
           outFile.println("   <name>Location " + i + "</name>");
           outFile.println("  <Point>");
           outFile.println("    <coordinates>" + arr[0]+","+arr[1] + ",0</coordinates>");
           outFile.println("  </Point>");
           outFile.println("</Placemark>");
        }
        endPortion(outFile);

     }catch(FileNotFoundException e){
     }
  }catch(ArrayIndexOutOfBoundsException e){
     System.out.println(fileName + " is not is correct format");

  }catch (FileNotFoundException e){
     System.out.println(fileName + " cannot be found!");
  }              
  }

  public static void topPortion(PrintStream file){
  file.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
  file.println("<kml xmlns=\"http://earth.google.com/kml/2.1\">");
  file.println("<Document>");
  file.println(" <name>Mystery Locations</name>");
  }

  public static void endPortion(PrintStream file){
  file.println("</Document>");
  file.println("</kml>");

  }

  }

你能告诉我这个错误是否与数组或 nextLine 函数有关吗?我试过广泛地寻找,似乎无法弄清楚。

【问题讨论】:

    标签: java arrays file while-loop


    【解决方案1】:

    这部分是你的问题:

    }catch(FileNotFoundException e){
    }
    

    如果找不到文件(无论出于何种原因),那么您的代码什么也不做。您应该打印出异常,以便您知道发生了什么,然后可以修复它:

    }catch(FileNotFoundException e){
        e.printStackTrace();
    }
    

    否则,尝试在每个动作之后添加一些调试代码,您的问题出在哪里会变得非常明显。

    例如在阅读String line = inFile.nextLine();后添加System.out.println("Line contains: " + line);

    【讨论】:

    • 是的!它说里面有一个空间。谢谢
    • 你知道我该如何解决这个问题吗?如果有文件末尾有空格?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-05
    相关资源
    最近更新 更多