如何在稍后的循环中使用变量

时间:2012-12-22 20:57:46

标签: java

我不确定这是否可能而且我是非常新的所以希望你们中的一些人可以对此有所了解,我有一个函数读取txt文件的所有内容然后在终端窗口打印出来,不过我希望能够将文本文件的数据存储在变量中,以便稍后可以使用它是否可能

下面是代码片段:

String mText; 
        while((mText = br.readLine()) != null) { 
            //Displays the contents of the file in terminal
            System.out.println(mText); 
        } 

因为我理解它一旦循环完成变量mText的内容在这种情况下被删除?

好吧,因为我的代码在下面,我想打印到打印机,该文件的内容,但当我运行它,我可以显示文件的内容很好,但它永远不会出现打印机选项框,我认为这将是问题,它看起来像我的代码中的其他东西:

import java.awt.*;
import java.awt.font.*;
import java.awt.geom.*;
import java.awt.print.*;
import java.text.*;
import java.io.*;
import javax.swing.*;

public class PrintText implements Printable {
    private static String mText;

    // Below the code will allow the user to select a file and then print out the contents of the file
    public static void main(String[] args) throws IOException {

        //selects the file
        JFileChooser chooser = new JFileChooser();
        chooser.showOpenDialog(null);
        File file = chooser.getSelectedFile();
        String filename = file.getName();
        //System.out.println("You have selected: " + filename);  testing to see if file seleected was right
        String path = file.getAbsolutePath();

        //Reads contents of file into terminal 
        //FileReader fr = new FileReader("filename");
        // FileReader fr = new FileReader("D:/Documents/" + "filename")); 

        FileReader fr = new FileReader(path); 
        BufferedReader br = new BufferedReader(fr); 
        String mText; 
        while((mText = br.readLine()) != null) { 
            //Displays the contents of the file in terminal
            System.out.println(mText); 
        } 
        //fr.close(); 
    } 

    //private static final String mText = 
    //    "This is a test to see if this text will be printed "; //This works perfectly fine

    AttributedString mStyledText = new AttributedString(mText);


    /**
     * Print a single page containing some sample text.
     */
    static public void printer(String args[]) {
        /* Get the representation of the current printer and 
         * the current print job.
         */
        PrinterJob printerJob = PrinterJob.getPrinterJob();
        /* Build a book containing pairs of page painters (Printables)
         * and PageFormats. This example has a single page containing
         * text.
         */
        Book book = new Book();
        book.append(new PrintText(), new PageFormat());
        /* Set the object to be printed (the Book) into the PrinterJob.
         * Doing this before bringing up the print dialog allows the
         * print dialog to correctly display the page range to be printed
         * and to dissallow any print settings not appropriate for the
         * pages to be printed.
         */
        printerJob.setPageable(book);
        /* Show the print dialog to the user. This is an optional step
         * and need not be done if the application wants to perform
         * 'quiet' printing. If the user cancels the print dialog then false
         * is returned. If true is returned we go ahead and print.
         */
        boolean doPrint = printerJob.printDialog();
        if (doPrint) {
            try {
                printerJob.print();
            } catch (PrinterException exception) {
                System.err.println("Printing error: " + exception);
            }
        }
    }

    /**
     * Print a page of text.
     */
    public int print(Graphics g, PageFormat format, int pageIndex) {
        /* We'll assume that Jav2D is available.
         */
        Graphics2D g2d = (Graphics2D) g;
        /* Move the origin from the corner of the Paper to the corner
         * of the imageable area.
         */
        g2d.translate(format.getImageableX(), format.getImageableY());
        /* Set the text color.
         */
        g2d.setPaint(Color.black);
        /* Use a LineBreakMeasurer instance to break our text into
         * lines that fit the imageable area of the page.
         */
        Point2D.Float pen = new Point2D.Float();
        AttributedCharacterIterator charIterator = mStyledText.getIterator();
        LineBreakMeasurer measurer = new LineBreakMeasurer(charIterator, g2d.getFontRenderContext());
        float wrappingWidth = (float) format.getImageableWidth();
        while (measurer.getPosition() < charIterator.getEndIndex()) {
            TextLayout layout = measurer.nextLayout(wrappingWidth);
            pen.y += layout.getAscent();
            float dx = layout.isLeftToRight()? 0 : (wrappingWidth - layout.getAdvance());
            layout.draw(g2d, pen.x + dx, pen.y);
            pen.y += layout.getDescent() + layout.getLeading();
        }
        return Printable.PAGE_EXISTS;
    }
}

这是我已经完成的原始代码,它在程序中打印出一个预先输入的文本,我试图在上面添加文件阅读器,现在它不起作用

import java.awt.*;
import java.awt.font.*;
import java.awt.geom.*;
import java.awt.print.*;
import java.text.*;
import java.io.*;
import javax.swing.*;
import java.util.List;
import java.util.ArrayList;

public class PrintText implements Printable {
   /** private static String mText;

    // Below the code will allow the user to select a file and then print out the contents of the file
    public static void main(String[] args) throws IOException {

        //selects the file
        JFileChooser chooser = new JFileChooser();
        chooser.showOpenDialog(null);
        File file = chooser.getSelectedFile();
        String filename = file.getName();
        //System.out.println("You have selected: " + filename);  testing to see if file seleected was right
        String path = file.getAbsolutePath();

        //Reads contents of file into terminal 
        //FileReader fr = new FileReader("filename");
        // FileReader fr = new FileReader("D:/Documents/" + "filename")); 

        FileReader fr = new FileReader(path); 
        BufferedReader br = new BufferedReader(fr); 
        List<String> list = new ArrayList<String>();
        while((mText = br.readLine()) != null) { 
            //Displays the contents of the file in terminal
            System.out.println(mText);
            list.add(mText); 
        } 
        //fr.close(); 
    } 
*/
    private static final String mText = 
        "This is a test to see if this text will be printed "; //This works perfectly fine

    AttributedString mStyledText = new AttributedString(mText);

    /**
     * Print a single page containing some sample text.
     */
    static public void main(String args[]) {
        /* Get the representation of the current printer and 
         * the current print job.
         */
        PrinterJob printerJob = PrinterJob.getPrinterJob();
        /* Build a book containing pairs of page painters (Printables)
         * and PageFormats. This example has a single page containing
         * text.
         */
        Book book = new Book();
        book.append(new PrintText(), new PageFormat());
        /* Set the object to be printed (the Book) into the PrinterJob.
         * Doing this before bringing up the print dialog allows the
         * print dialog to correctly display the page range to be printed
         * and to dissallow any print settings not appropriate for the
         * pages to be printed.
         */
        printerJob.setPageable(book);
        /* Show the print dialog to the user. This is an optional step
         * and need not be done if the application wants to perform
         * 'quiet' printing. If the user cancels the print dialog then false
         * is returned. If true is returned we go ahead and print.
         */
        boolean doPrint = printerJob.printDialog();
        if (doPrint) {
            try {
                printerJob.print();
            } catch (PrinterException exception) {
                System.err.println("Printing error: " + exception);
            }
        }
    }

    /**
     * Print a page of text.
     */
    public int print(Graphics g, PageFormat format, int pageIndex) {
        /* We'll assume that Jav2D is available.
         */
        Graphics2D g2d = (Graphics2D) g;
        /* Move the origin from the corner of the Paper to the corner
         * of the imageable area.
         */
        g2d.translate(format.getImageableX(), format.getImageableY());
        /* Set the text color.
         */
        g2d.setPaint(Color.black);
        /* Use a LineBreakMeasurer instance to break our text into
         * lines that fit the imageable area of the page.
         */
        Point2D.Float pen = new Point2D.Float();
        AttributedCharacterIterator charIterator = mStyledText.getIterator();
        LineBreakMeasurer measurer = new LineBreakMeasurer(charIterator, g2d.getFontRenderContext());
        float wrappingWidth = (float) format.getImageableWidth();
        while (measurer.getPosition() < charIterator.getEndIndex()) {
            TextLayout layout = measurer.nextLayout(wrappingWidth);
            pen.y += layout.getAscent();
            float dx = layout.isLeftToRight()? 0 : (wrappingWidth - layout.getAdvance());
            layout.draw(g2d, pen.x + dx, pen.y);
            pen.y += layout.getDescent() + layout.getLeading();
        }
        return Printable.PAGE_EXISTS;
    }
}

3 个答案:

答案 0 :(得分:2)

  

一旦循环完成变量的内容,我就明白了   在这种情况下,mText会被删除吗?

如果从文本文件中读取多行,则以下写入将覆盖以前的所有写入。因此,您的变量mText将只包含最后一行读取。

如果您希望在循环结束后可以访问读取的所有行,则可以将这些行存储在某个集合中。

理想情况下,您可以在这种情况下创建List<String>,并将数据存储在其中: -

List<String> list = new ArrayList<String>();
while((mText = br.readLine()) != null) { 
        //Displays the contents of the file in terminal
        System.out.println(mText);
        list.add(mText); 
} 

现在在while循环之外,您可以从列表中访问您的数据。

答案 1 :(得分:0)

没有。变量在方法的范围内定义,因此在声明并给出值之后,它的值在方法中的任何位置都可用。

但是,你拥有它的代码可能没有为变量赋值,因为readline()可能抛出IOException,所以你不能在这个循环之后使用变量 - 你会得到一个“可能未分配的变量“编译错误。要解决此问题,请在声明时初始化变量:

String mText = null;

答案 2 :(得分:0)

如果你想保留所有行,你必须以这种方式存储它们:

    StringBuilder sb= new StringBuilder();
    String mText;
    while ((mText = br.readLine()) != null) {
        //Displays the contents of the file in terminal
        System.out.println(mText);
        sb.append(mText).append('\n');
    }
    // now the whole content of the BufferedReader is stored in sb.