Search code examples
javajsoneclipselong-integertwitter4j

How do I save a Java long value to file?


So iv'e been trying to find a way of saving a "long" value to a file. I'm using the Twitter4j packages. When I get a list of Followers IDs, it saves them into a long variable. I can do a System Out Print of the value, but I can't write it to a file. I'll show it in the code.

//First of course I put all this stuff in. This is not the Problem though.
String consumerKey = "************"; 
String consumerSecret = "**************";
String accessToken = "*******************************";
String accessTokenSecret = "*****************";
TwitterFactory twitterFactory = new TwitterFactory();
Twitter twitter = twitterFactory.getInstance();
twitter.setOAuthConsumer(consumerKey, consumerSecret);
twitter.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));

//Then add the cursor value and call the command
long cursor = -1;                
IDs ids = twitter.getFollowersIDs("username_foo",cursor);

//If I want to the next cursor value
System.out.print(ids.getNextCursor());

//It works to do a system out print of the IDs
for (long id : ids.getIDs()) {System.out.println(id);}

//So how do I write it into a file? This sure don't work.
file.write(getIDs());

Just in case you are wondering, I am using FileOutputStream and DataOutputSream.


Solution

  • To write it line wise to a plain text file, use a BufferedWriter and write each line of the values like so:

    File outputFile = new File("/path/to/file.txt");
    Writer writer = new BufferedWriter(
                    new OutputStreamWriter(
                    new FileOutputStream(outputFile), "UTF-8"));
    for (long id : ids.getIDs()) {
        writer.write(id + "\n");
    }
    writer.close();
    

    (a DataOutputStream in contrast will not give you a human-readable format).