【问题标题】:Java: Converting issues [duplicate]Java:转换问题[重复]
【发布时间】:2012-06-03 19:13:15
【问题描述】:

可能重复:
How to create a Java String from the contents of a file

我正在制作一个 java 程序来读取文件并创建文件以供娱乐。我想知道如何从文件中读取并将其设置为字符串变量。或者将扫描仪变量转换为字符串变量,这里以部分编码为例:

    private Scanner x;
    private JLabel label;
    private String str;

    public void openfile(String st){


        try{
            x = new Scanner(new File(st));
        }
        catch(Exception e){
            System.out.println("Error: File Not Found");
        }
    }

【问题讨论】:

  • Stack Overflow 不是学习语言基础知识的地方;你应该考虑买一本关于 Java 的入门书,或者阅读官方教程:docs.oracle.com/javase/tutorial/essential/io/fileio.html
  • 我实际上正在关注 thenewboston 在 youtube 上的教程系列。他只是没有解释扫描仪到字符串的转换,除非我错过了。
  • 我希望人们对新人更友善。
  • @OliCharlesworth,是的,但这可以用一种友好且不那么令人沮丧的方式说出来。
  • IMO 这不是一个好/不好的问题,这是一个监管 SO 知识库的问题,至少尝试保持高质量。这是任何合理的自学者只要稍加努力就能发现的东西,因此我同意这不是一个很好的选择。在 Oli 的回应中,我没有发现任何不友好的地方——只是很严肃。

标签: java string


【解决方案1】:

这是一个强大的oneliner。

String contents = new Scanner(file).useDelimiter("\\Z").next(); 

【讨论】:

  • :O 使用分隔符是什么东西?我还在学习
  • @AaronLeslie,见javadoc of the method
  • @KazekageGaara,在上下文中非常合适!我最初误判了 OP 目前的理解水平。但是我仍然在这里留下这个答案,希望有人会觉得它有用。
  • @AaronLeslie,这是一种高级技术(涉及一种称为正则表达式的东西),也许在这个阶段最好忽略它。
【解决方案2】:

这样做的好方法是使用 Apache commons IOUtils 将 inputStream 复制到 StringWriter... 类似

StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();

如果您不想混合使用 Streams 和 Writer,也可以使用 ByteArrayOutputStream

http://commons.apache.org/io/api-1.4/org/apache/commons/io/IOUtils.html#toString%28java.io.InputStream,%20java.lang.String%29

【讨论】:

    【解决方案3】:

    或者你甚至可以试试这个:

     ArrayList <String> theWord = new ArrayList <String>();
                //while it has next ..
                while(x.hasNext()){
                    //Initialise str with word read
                    String str=x.next();
                    //add to ArrayList
                    theWord.add(str);
    
                }
                //print the ArrayList
                System.out.println(theWord);
    
            }
    

    【讨论】:

    • 我试图在一个没有 jsut a system.out.println 的盒子上打印它:P
    • 嗯,上面的 ArrayList 将包含该文件中的所有单词,将其打印到任何你想要的地方。
    【解决方案4】:

    这是一个如何将文件读入字符串的示例:

    public String readDocument(File document)
            throws SystemException {
        InputStream is = null;
        try {
            is = new FileInputStream(document);
            long length = document.length();
            byte[] bytes = new byte[(int) length];
            int offset = 0;
            int numRead = 0;
            while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
                offset += numRead;
            }
            if (offset < bytes.length) {
                throw new SystemException("Could not completely read file: " + document.getName());
            }
            return new String(bytes);
        } catch (FileNotFoundException e) {
            LOGGER.error("File not found exception occurred", e);
            throw new SystemException("File not found exception occurred.", e);
        } catch (IOException e) {
            LOGGER.error("IO exception occurred while reading file.", e);
            throw new SystemException("IO exception occurred while reading file.", e);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    LOGGER.error("IO exception occurred while closing stream.", e);
                }
            }
        }
    }
    

    【讨论】:

    • java uuuggghh 的菜鸟脑子很疼
    【解决方案5】:
    BufferedReader in =new BufferedReader(new FileReader(filename));
        String strLine;
        while((strLine=in.readLine())!=null){
        //do whatever you want with that string here
        }
    

    【讨论】:

      猜你喜欢
      • 2017-01-30
      • 1970-01-01
      • 1970-01-01
      • 2019-11-26
      • 1970-01-01
      • 2018-06-10
      • 2016-12-03
      • 1970-01-01
      • 2020-08-05
      相关资源
      最近更新 更多