-5

Possible Duplicate:
How to create a Java String from the contents of a file

I am making a java program to read a file and to create files for fun. I was wondering how to read from a file and set it to a string variable. Or to convert a scanner variable to a string variable heres part of the coding as an example:

    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");
        }
    }
Community
  • 1
  • 1
  • 4
    Stack Overflow is not the place to be taught language basics; you should consider getting an introductory book on Java, or reading the official tutorial: http://docs.oracle.com/javase/tutorial/essential/io/fileio.html – Oliver Charlesworth Jun 03 '12 at 19:15
  • 1
    Im actually following a tutorial series on youtube by thenewboston. He just didnt explain conversion of scanner to string unless i missed it. – Aaron Leslie Jun 03 '12 at 19:18
  • 3
    I wish people were kinder towards newcomers. – missingfaktor Jun 03 '12 at 19:18
  • @missingfaktor: My intention is not to be unkind. But the OP is asking a question that is answered in about Chapter 4 of any introductory book on Java. – Oliver Charlesworth Jun 03 '12 at 19:20
  • 1
    @OliCharlesworth, yes, but that can be said in a friendly and less discouraging way. – missingfaktor Jun 03 '12 at 19:24
  • 2
    IMO it's not a nice/not-nice issue, it's an issue of policing the SO knowledge base and at least attempt to keep the quality high. This is something any reasonable self-learner would be able to discover with even a modicum of effort, hence I agree that it's not a great fit. I didn't find anything un-friendly in Oli's response--it's just austere. – Dave Newton Jun 03 '12 at 19:24
  • 1
    @DaveNewton, I am also referring to the raining downvotes. They are unnecessary and discouraging. – missingfaktor Jun 03 '12 at 19:34
  • I agree to a degree, but the original poster's latest edit, `(Attention: I already gave up on this program its pissing me off i keep running into new errors.)`, forced me to down-vote him just now. Why help if all he's going to do is give up? And that in spite of getting tons of help with 5 answers no less. To the original poster: buy a decent intro to Java book, and go through it chapter by chapter and page by page. You need to learn to walk first making small steps to start with. Consider the Head First book as a decent intro (if its style jibes with your learning style). – Hovercraft Full Of Eels Jun 03 '12 at 19:36
  • 1
    @OP, your recent title edit is inappropriate. – missingfaktor Jun 03 '12 at 19:43
  • @missingfaktor First of all, downvoting is asynchronous: people less-inclined to downvote if it's already been downvoted won't necessarily know it's been downvoted. Second of all, downvoting is a direct indicator of question quality--if a question isn't good quality (IMO this one qualifies, although I didn't downvote) what should an SO user do? "Downvote" is the correct answer, in general. Following SO policies isn't "being unkind", it's "using the site as intended". Not everything is a personal attack. – Dave Newton Jun 03 '12 at 19:46
  • 1
    @missingfaktor And *upvoting* clearly-bad questions to "compensate" is attempting to right one (perceived) wrong with another. – Dave Newton Jun 03 '12 at 19:47
  • @DaveNewton, I did it anyway. In my early days at Stackoverflow, I was similarly downvoted, and I did not find it encouraging. – missingfaktor Jun 03 '12 at 19:49
  • 1
    @missingfaktor We all get to decide what's appropriate behavior for ourselves--nothing wrong with that. I can only up/downvote once, and up until now have remained neutral, hoping the OP would simply fix the question. 'Tis not to be. – Dave Newton Jun 03 '12 at 19:50

5 Answers5

1

Here is a mighty oneliner.

String contents = new Scanner(file).useDelimiter("\\Z").next(); 
missingfaktor
  • 88,931
  • 61
  • 278
  • 362
  • :O whats the use delimiter thing? Im still kinda learning – Aaron Leslie Jun 03 '12 at 19:20
  • @AaronLeslie, see the [javadoc of the method](http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html#useDelimiter(java.lang.String)). – missingfaktor Jun 03 '12 at 19:27
  • @missingfaktor [something you already know](http://goo.gl/cG6sh) – Kazekage Gaara Jun 03 '12 at 19:28
  • @KazekageGaara, very appropriate in the context! I initially misjudged OP's current level of understanding. However I am still leaving this answer here hoping someone might find it useful. – missingfaktor Jun 03 '12 at 19:32
  • @AaronLeslie, this is a bit of an advanced technique (involves something called regular expressions), and perhaps it's best to ignore it at this stage. – missingfaktor Jun 03 '12 at 19:32
1

nice way to do this is using Apache commons IOUtils to copy the inputStream into a StringWriter... something like

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

Alternatively, you could use ByteArrayOutputStream if you don't want to mix your Streams and Writers

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

Ruzbeh Irani
  • 2,178
  • 17
  • 10
0

Or you can even try this:

 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);

        }
Kazekage Gaara
  • 14,764
  • 14
  • 55
  • 105
0

Here is an example how to read file into string:

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);
            }
        }
    }
}
Paulius Matulionis
  • 22,485
  • 21
  • 100
  • 140
0
BufferedReader in =new BufferedReader(new FileReader(filename));
    String strLine;
    while((strLine=in.readLine())!=null){
    //do whatever you want with that string here
    }
Jimmy
  • 2,499
  • 20
  • 31