I/O Java required int - java

I am trying to use I/O to give a report on the stock that I need (if the stock is below 8).
It tells me it requires an int for myShop.listLowStockToFile());; when I add a number it tells me that 'void is not allowed here'. How can I fix this?
public void listLowStockToFile(int threshhold)
{
System.out.println("****The Stock that is getting low is: " + " Minimum " +threshhold + " Report for Bob Shaw****\n");
for (Item nextItem : items)
{
if(nextItem.getNuminStock() < threshhold)
{
System.out.println(nextItem);
}
}
}
public class Report {
public static void main(String[] args) {
Shop myShop = new Shop();
CD cd1 = new CD("Abba Gold", "Abba", 15);
myShop.addItem(cd1);
Game game1 = new Game("Chess", 2, 39.95);
myShop.addItem(game1);
ElectronicGame eg1 = new ElectronicGame("Shrek", "PS2", 1, 79.50);
myShop.addItem(eg1);
ElectronicGame eg2 = new ElectronicGame("Doom", "PC", 2, 30.20);
myShop.addItem(eg2);
ElectronicGame eg3 = new ElectronicGame("AFL", "PS2", 2, 49.95);
myShop.addItem(eg3);
cd1.receiveStock(3);
game1.receiveStock(5);
eg1.receiveStock(10);
eg2.receiveStock(1);
cd1.receiveStock(7);
cd1.sellCopy(true);
cd1.sellCopy(true);
eg2.sellCopy(true);
myShop.listItems();
myShop.listLowStockToFile(8);
myShop.listGamesByPlatform("PS2");
myShop.calcTotalSales();
Game game2 = new Game("Chess", 2, 39.95);
myShop.addItem(game2);
eg2.sellCopy(false);
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("LowStock.txt"));
writer.write("Report dated" + new Date() + "\n");
writer.write(myShop.listLowStockToFile()); // This line.
writer.close();
System.out.println("Report finished");
} catch (Exception ex) {
System.out.println("File I/O error" + ex);
}
}
}

You need listLowStockToFile to return a String:
public String listLowStockToFile(int threshhold) {
String rtn = "****The Stock that is getting low is: " + " Minimum " +threshhold + " Report for Bob Shaw****\n";
for (Item nextItem : items) {
if(nextItem.getNuminStock() < threshhold) {
rtn += nextItem.toString() + "\n";
}
}
System.out.print(rtn);
return rtn;
}
The reason is that BufferedWritter.write takes a String as an argument.

Related

Parsing from MealMaster files in Java

Currently, I'm am trying to parse from MealMaster files, but I am having an issue where Ingredients are being parsed as:
"Inch thick" due to the next line not having a quantity or unit, and carrying on from the previous
Also, I'm finding ingredients that are listed as "ingredient1 or ingredient2" and I'm not sure how to catagorise these in the parser
Here is an example of a file I'm parsing from and my code below
https://pastebin.com/fhkRczya
public void readIngredients() {
try {
Remover remover = new Remover();
ArrayList<Ingredient> ing = new ArrayList<Ingredient>();
while(!( "".equals(line.trim()))) {
parsedIngredients = line + "\n";
if(!line.contains("---") && !line.contains(":")) {
Ingredient currentIng = splitLine();
if(currentIng.getQuantity().length() == 0 && !ing.isEmpty()) {
Ingredient lastIng = ing.get(ing.size()-1);
if (currentIng.getName().toLowerCase().contains("inch") ) {
//System.out.println(currentIng.getName());
lastIng.setOther(lastIng.getOther() + "," + currentIng.getQuantity() + "," +currentIng.getName());
//System.out.println("OTher " + lastIng.getOther());
}else{
String lastIngName = lastIng.getName();
String addName = lastIngName + " " + currentIng.getName();
lastIng.setName(addName);
lastIng = remover.removeTo(unitWords,lastIng);
lastIng = remover.removeCustomWords(lastIng);
}
}else if (currentIng.getName().startsWith("-") || currentIng.getName().startsWith("For") ){
if(ing.size()>0) {
Ingredient lastIng = ing.get(ing.size()-1);
lastIng.setOther(currentIng.getQuantity() + " " + currentIng.getName());
}
}else {
currentIng = remover.removeTo(unitWords,currentIng);
currentIng = remover.removeCustomWords(currentIng);
//currentIng.setName(currentIng.getName().replace(",", ""));
System.out.println(currentIng.getName());
ing.add(currentIng);
}
}
line = reader.readLine();
}
for(int i = 0; i < ing.size();i++) {
removeCommaColon(ing.get(i));
}
for(int i = 0; i<ing.size();i++) {
ingredientsString = ingredientsString + ing.get(i).getName() + "|" + currentRecipe.getTitle() + " \n";
//ingredientsString = ingredientsString + currentRecipe.getTitle() + "\n";
}
currentRecipe.setIngredients(ing);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Nesting Marshalling while using JAXB & XML Annotation involving list of elements

Many of you have can help me with this question. I went through many question answers on stackoverflow, but in someway the code which I wrote doesnt seem to work the way I want it to work.
Any help will be appreciated.
I also came across this excellent article http://blog.bdoughan.com/2010/09/jaxb-collection-properties.html and it explained to me a lot of things.
I tried implementing it but not getting the required format of xml. Any help will be much appreciated.
Thank you.
Below I am posting the code :
There are 2 classes in my program:
DSC.java and Identity.java , The former class sets the values by calling the get/set methods in the Identity class.
::::::::::Identity.java::::::::::::
#XmlRootElement(name="LabbuddyArray")
public class Identity {
public String toString()
{
return "DSC_XML_OUTPUT [Company_name=" + company_name + ", Model_Number=" + model_number + ", Serial_Number=" + serial_number + ", New_BIAS=" + new_bias +", New_TEMP=" + new_temp + "]";
}
//DECLARE VARIABLES
String company_name;
String model_number;
String serial_number;
String port_number;
float photo_current;
float actual_bias;
float new_bias;
float actual_temp;
float new_temp;
List<String> slots;
public Identity(){}
//DECLARING CLASSES FOR XML FORMATTING
//GETTING AND SETTING SLOTS TO XML
#XmlElementWrapper
#XmlElement(name="slot")
public List<String> getSlots (){
return slots;
}
public void setSlots (List<String> slots){
this.slots = slots;
}
public String getIdentityCompanyName() {
return company_name;
}
#XmlElement(name="setIdentityCompanyName")
public void setIdentityCompanyName(String identity_company_name) {
this.company_name = identity_company_name;
}
//GETTING AND SETTING MODEL_NUMBER TO XML
public String getIdentityModelNumber() {
return model_number;
}
#XmlElement(name="setIdentityModelNumber")
public void setIdentityModelNumber(String model_number) {
this.model_number = model_number;
}
//GETTING AND SETTING SERIAL_NUMBER TO XML
public String getIdentitySerialNumber() {
return serial_number;
}
#XmlElement(name="setIdentitySerialNumber")
public void setIdentitySerialNumber(String serial_number) {
this.serial_number = serial_number;
}
//GETTING AND SETTING PORT_NUMBER TO XML
public String getIdentityPortNumber() {
return port_number;
}
#XmlElement (name="setIdentityPortNumber")
public void setIdentityPortNumber(String port_number) {
this.port_number = port_number;
}
//GETTING AND SETTING PHOTOCURRENT TO XML
public float getMonitorPhotoCurrent() {
return photo_current;
}
#XmlElement(name="setMonitorPhotoCurrent")
public void setMonitorPhotoCurrent(float photo_current) {
this.photo_current = photo_current;
}
//GETTING AND SETTING BIAS TO XML
//ACTUAL BIAS (READ)
public float getControlActualBias() {
return actual_bias;
}
#XmlElement (name="setControlActualBias")
public void setControlActualBias(float actual_bias) {
this.actual_bias = actual_bias;
}
//NEW BIAS (WRITE)
public float getControlNewBias(){
return new_bias;
}
#XmlElement (name="setControlNewBias")
public void setControlNewBias(float new_bias){
this.new_bias = new_bias;
}
//GETTING AND SETTING TEMP TO XML
//ACTUAL TEMP (READ)
public float getControlActualTemp() {
return actual_temp;
}
#XmlElement (name="setControlActualTemp")
public void setControlActualTemp(float actual_temp) {
this.actual_temp = actual_temp;
}
//NEW TEMP (WRITE)
public float getControlNewTemp(){
return new_temp;
}
#XmlElement(name ="setControlNewTemp")
public void setControlNewTemp(float new_temp){
this.new_temp = new_temp;
}
}
:::::::::::DSC.java::::::::::::
public class Dsc {
public static void main(String[] args) throws InterruptedException {
//INITIALIZING SCANNER TO TAKE INPUTS
Scanner input = new Scanner(System.in);
//CALLING ALL FUNCTIONS
Identity identity = new Identity();
List<String> strings = new ArrayList<String>(2);
strings.add("1");
identity.setSlots(strings);
//CREATING SERIAL PORT OBJECT
SerialPort serialPort = new SerialPort("COM4");
//GETTING SERIALPORTS
String[] portNames = SerialPortList.getPortNames();
for(int i = 0; i < portNames.length; i++)
{
System.out.println("Port Available on this machine: " +portNames[i]);
}
identity.setIdentityPortNumber("COM4");
//STARTING TRY BLOCK TO CATCH ERRORS THROUGHOUT THE EXECUTION
try
{
//OPENING PORT AND ASSIGNING PARAMETERS FOR COMMUNICATION
System.out.println("Port opened: " + serialPort.openPort());
System.out.println("Params setted: " + serialPort.setParams(57600, 8, 1, 0));
System.out.println("--------------------------------------------------------");
//IDENTIFYING THE COMPANY NAME ; MODEL NUMBER ; SERIAL NUMBER ; PORT NUMBER
System.out.println("Passing *IDN? to identify the Device: " +serialPort.writeString("*IDN? \n"));
Thread.sleep(500);
String str = serialPort.readString();
System.out.println("The Device ID is: " +str);
String[] deviceid = str.split(",");
System.out.println("Company :" + deviceid[0]);
identity.setIdentityCompanyName(deviceid[0]);
System.out.println("Model Number :" + deviceid[1]);
identity.setIdentityModelNumber(deviceid[1]);
System.out.println("Serial Number :" + deviceid[2]);
identity.setIdentitySerialNumber(deviceid[2]);
System.out.println("--------------------------------------------------------");
//IDENTIFYING THE PHOTOCURRENT
System.out.println("Passing MEAS:IDC? to identify the Photocurrent: " +serialPort.writeString("MEAS:IDC? \n"));
Thread.sleep(500);
String str1 = serialPort.readString();
System.out.println("The Photocurrent is :" +str1);
float photoCurrent = Float.parseFloat(str1);
identity.setMonitorPhotoCurrent(photoCurrent);
System.out.println("--------------------------------------------------------");
//IDENTIFYING THE ACTUAL BIAS
System.out.println("Passing MEAS:BIAS? to identify the Actual BIAS: " +serialPort.writeString("MEAS:BIAS? \n"));
Thread.sleep(500);
String str2 = serialPort.readString();
System.out.println("The Actual BIAS is :" +str2);
float control_actualBias = Float.parseFloat(str2);
identity.setControlActualBias(control_actualBias);
System.out.println("--------------------------------------------------------");
//SETTING THE BIAS
System.out.println("Set the Bias to ?");
float setBias = input.nextFloat();
System.out.println("Setting the user input BIAS to " +setBias +": " +serialPort.writeString("INP:BIAS " +setBias +"\n" ));
Thread.sleep(500);
identity.setControlNewBias(setBias);
System.out.println("--------------------------------------------------------");
//IDENTIFYING THE ACTUAL TEMPERATURE
System.out.println("Passing MEAS:TEMP? to identify the Temperature: " +serialPort.writeString("MEAS:TEMP? \n"));
Thread.sleep(500);
String str3 = serialPort.readString();
System.out.println("The Actual TEMP is: " +str3);
float actualTemp = Float.parseFloat(str3);
identity.setControlActualTemp(actualTemp);
System.out.println("--------------------------------------------------------");
//SETTING THE TEMPERATURE
System.out.println("Set the new TEMP to ?");
float setTemp = input.nextFloat();
System.out.println("Setting the user input TEMP to " +setTemp +": " +serialPort.writeString("INP:TEMP " +setTemp +"\n" ));
Thread.sleep(500);
identity.setControlNewTemp(setTemp);
System.out.println("--------------------------------------------------------");
}
catch (SerialPortException ex)
{
System.out.println(ex);
}
//STARTING THE JAXBCONTEXT & JAXBMARSHALLER CODE TO WRITE OUTPUT IN XML FILE
try
{
File file = new File("C:\\xampp\\htdocs\\StateMachine.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Identity.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(identity, file);
jaxbMarshaller.marshal(identity, System.out);
}
catch (JAXBException e)
{
e.printStackTrace();
}
}
}
:::::::: Current XML output ::::::::
<LabbuddyArray>
<setControlActualBias>5.999</setControlActualBias>
<setControlActualTemp>21.9</setControlActualTemp>
<setControlNewBias>5.0</setControlNewBias>
<setControlNewTemp>23.0</setControlNewTemp>
<setIdentityCompanyName>DSC</setIdentityCompanyName>
<setIdentityModelNumber>HLPD Lab Buddy</setIdentityModelNumber>
<setIdentityPortNumber>COM4</setIdentityPortNumber>
<setIdentitySerialNumber>50311602</setIdentitySerialNumber>
<setMonitorPhotoCurrent>0.0</setMonitorPhotoCurrent>
<slots>
<slot>1</slot>
</slots>
</LabbuddyArray>
::::::Required XML OUTPUT::::::
<LabbuddyArray>
<slot1>
<setControlActualBias></setControlActualBias>
<setControlActualTemp></setControlActualTemp>
<setControlNewBias></setControlNewBias>
<setControlNewTemp></setControlNewTemp>
<setIdentityCompanyName></setIdentityCompanyName>
<setIdentityModelNumber></setIdentityModelNumber>
<setIdentityPortNumber></setIdentityPortNumber>
<setIdentitySerialNumber></setIdentitySerialNumber>
<setMonitorPhotoCurrent></setMonitorPhotoCurrent>
</slot1>
<slot2>
<setControlActualBias></setControlActualBias>
<setControlActualTemp></setControlActualTemp>
<setControlNewBias></setControlNewBias>
<setControlNewTemp></setControlNewTemp>
<setIdentityCompanyName></setIdentityCompanyName>
<setIdentityModelNumber></setIdentityModelNumber>
<setIdentityPortNumber></setIdentityPortNumber>
<setIdentitySerialNumber></setIdentitySerialNumber>
<setMonitorPhotoCurrent></setMonitorPhotoCurrent>
</slot2>
</LabbuddyArray>
Then you should have something like this...
#XmlRootElement(name="LabbuddyArray")
public class Identity {
List<Slots> slots;
#XmlElement(name="slot")
public List<Slots> getSlots() {
return slots;
}
public void setSlots(List<Slots> slots) {
this.slots = slots;
}
}
Create a class 'Slots', copy all the elements and mapping to it.
And in the Dsc class populate the values as required.
Identity identity = new Identity();
List<Slots> slots = new ArrayList<Slots>();
Slots slot = new Slots();
slot.setControlActualBias(Float.valueOf("1.23"));
slots.add(slot);
slot = new Slots();
slot.setControlActualBias(Float.valueOf("1.24"));
slots.add(slot);
identity.setSlots(slots);
This will yield you the response similar to the one below.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<LabbuddyArray>
<slot>
<setControlActualBias>1.23</setControlActualBias>
<setControlActualTemp>0.0</setControlActualTemp>
<setControlNewBias>0.0</setControlNewBias>
<setControlNewTemp>0.0</setControlNewTemp>
<setMonitorPhotoCurrent>0.0</setMonitorPhotoCurrent>
</slot>
<slot>
<setControlActualBias>1.24</setControlActualBias>
<setControlActualTemp>0.0</setControlActualTemp>
<setControlNewBias>0.0</setControlNewBias>
<setControlNewTemp>0.0</setControlNewTemp>
<setMonitorPhotoCurrent>0.0</setMonitorPhotoCurrent>
</slot>
</LabbuddyArray>

Cannot get Txt file to create from code

Good day. I am trying to get the code below to write to a txt file. Yet, I cannot get it to. It just prints the code within the ("") on the output section. My goal is to create the text file to store the output data to retrieve later.
public class Charlesshaw3Test {
public static void main(String[] args) throws Exception{
**//checking id command line argument provided
if(args.length==0) {
System.out.println("C:\\Users\\bryon\\Desktop\\Java Programming");
System.exit(1);
}
String fileName = args[0];
BufferedWriter out = null;
try {
FileWriter fstream = new FileWriter(fileName);
out = new BufferedWriter(fstream);
}
catch (IOException ex) {
System.out.println("\nCould not create file: "+ fileName+".");
System.exit(1);
}**
//a) 10 Instances of the violin testing.
CharlesShaw3Tst voilin[] = new CharlesShaw3Tst[10];
for (int i = 0; i < 10; i++) {
out.write("\n\n***Creating new violin object [" + (i + 1) + "]***");
voilin[i] = new CharlesShaw3Tst();
out.write("\nCreated");
//b) tune your instruments,
out.write("\nchecking if tuned?");
out.write("\nVoilin tuned? " + voilin[i].isTuned());
out.write("\nTuning...");
voilin[i].setTuned(true);
out.write("\nVoilin tuned? " + voilin[i].isTuned());
//c) Start playing your instrument,
out.write("\nVoilin playing? " + voilin[i].isPlaying());
out.write("\nVoilin tuned? " + voilin[i].isTuned());
out.write("\nCalling playVoilin method");
voilin[i].playViolin();
out.write("\nVoilin playing? " + voilin[i].isPlaying());
// d) Call your unique method, and
int num = voilin[i].getNumString();
out.write("\nNumber of strings: " + num);
out.write("\nString name: ");
String strings[] = voilin[i].getviolinStrings();
for (int s = 0; s < num; s++) {
out.write(strings[s] + " ");
}
out.write("\n");
//e) Stop playing your instruments.
out.write("\nStopping playing..");
voilin[i].stopViolin();
out.write("\nVoilin playing? " + voilin[i].isPlaying());
out.write("\nStopping tuning..");
voilin[i].stopTuneViolin();
out.write("\nVoilin tuned? " + voilin[i].isTuned());
}
//Close the output stream
out.close();
}
}
Try using FileWriter's append method:
try {
FileWriter writer = new FileWriter(file);
writer.append("Your string");
//Append all strings
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
The previous program it is referring to is:
public class CharlesShaw3Tst {
private final int numString = 5; // number of strings
private final String violinStrings[] = {"E", "B", "G", "D", "A"}; //an array of strings
//fields to determine if the instrument is tuned,
private boolean tuned;
//and if the instrument is currently playing.
private boolean playing;
//A constructor method that set the tuned and currently playing fields to false.
public CharlesShaw3Tst() {
this.tuned = false;
this.playing = false;
}
// Other methods
public boolean isPlaying() {
return playing;
}
public void setPlaying(boolean playing) {
this.playing = playing;
}
public boolean isTuned() {
return tuned;
}
public void setTuned(boolean isTuned) {
this.tuned = isTuned;
}
public void playViolin() {
System.out.println("The violin is now playing.");
playing = true;
}
public void stopViolin() {
System.out.println("The violin is now playing.");
playing = true;
}
public void tuneViolin() {
System.out.println("The violin is tuned.");
tuned = true;
}
public void stopTuneViolin() {
System.out.println("The violin is tuned.");
tuned = false;
}
public int getNumString() {
return this.numString ;
}
public String[] getviolinStrings() {
return violinStrings;
}
}

Twitter Stream API get 100 status and stop the exceution

I am using twitter4j twitter Streaming API to get the tweets for the specific tag.
I am having number of keywords. I want to search the 100 tweets thats containing that tag
currently what i am doing is i wrote code for getting the tweets for single word
public class StreamAPI {
public static void main(String[] args) {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true);
cb.setOAuthConsumerKey("xxxx");
cb.setOAuthConsumerSecret("xxxxx");
cb.setOAuthAccessToken("xxxx");
cb.setOAuthAccessTokenSecret("xxxx");
cb.setUseSSL(true);
cb.setUserStreamRepliesAllEnabled(true);
TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();
twitterStream.setOAuthAccessToken(accestoken);
StatusListener listener = new StatusListener() {
int countTweets = 0;
public void onStatus(Status status) {
System.out.println("#" + status.getUser().getScreenName() + " - " + status.getText());
countTweets++;
System.out.println(countTweets);
}
public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
}
public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
}
public void onScrubGeo(long userId, long upToStatusId) {
System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
}
#Override
public void onStallWarning(StallWarning stallWarning) {
//To change body of implemented methods use File | Settings | File Templates.
}
public void onException(Exception ex) {
ex.printStackTrace();
}
};
FilterQuery fq = new FilterQuery();
String keywords[] = {"ipl"};
fq.track(keywords);
twitterStream.addListener(listener);
twitterStream.filter(fq);
}
}
how would i stop the process after it reaches the count 100 and should return that 100 tweet as list.
Please help me.
see the below code maybe helpfull for you
String token= "Key Word";
Query query = new Query(token);
FileWriter outFile = new FileWriter(token.replaceAll("^#","").concat(".txt"), true);
int numberOfTweets = 1500;
long lastID = Long.MAX_VALUE;
ArrayList<Status> tweets = new ArrayList<Status>();
while (tweets.size () < numberOfTweets) {
if (numberOfTweets - tweets.size() > 100)
query.setCount(100);
else
query.setCount(numberOfTweets - tweets.size());
try {
QueryResult result = twitter.search(query);
tweets.addAll(result.getTweets());
System.out.println("Gathered " + tweets.size() + " tweets");
for (Status t: tweets)
if(t.getId() < lastID) lastID = t.getId(); }
catch (TwitterException te) {
System.out.println("Couldn't connect: " + te); };
query.setMaxId(lastID-1);
}
PrintWriter out1 = new PrintWriter(outFile);
for (int i = 0; i < tweets.size(); i++) {
Status t = (Status) tweets.get(i);
GeoLocation loc = t.getGeoLocation();
String user = t.getUser().getScreenName();
String msg = t.getText();
String time = "";
if (loc!=null) {
Double lat = t.getGeoLocation().getLatitude();
Double lon = t.getGeoLocation().getLongitude();
System.out.println(i + " USER: " + user + " wrote: " + msg + " located at " + lat + ", " + lon);}
else
// System.out.println(i + " USER: " + user + " wrote: " + msg.replaceAll("\n",""));
out1.append(i + " USER: " + user + " wrote: " +msg.replaceAll("\n"," ") );
out1.print("\n");
}
System.out.println("file write succefully");

Download a Large Number of Files Using the Java SDK for Amazon S3 Bucket

I have a large number of files that need to be downloaded from an S3 bucket. My problem is similar to this article except I am trying to run it in Java.
public static void main(String args[]) {
AWSCredentials myCredentials = new BasicAWSCredentials("key","secret");
TransferManager tx = new TransferManager(myCredentials);
File file = <thefile>
try{
MultipleFileDownload myDownload = tx.downloadDirectory("<bucket>", null, file);
System.out.println("Transfer: " + myDownload.getDescription());
System.out.println(" - State: " + myDownload.getState());
System.out.println(" - Progress: " + myDownload.getProgress().getBytesTransfered());
while (myDownload.isDone() == false) {
System.out.println("Transfer: " + myDownload.getDescription());
System.out.println(" - State: " + myDownload.getState());
System.out.println(" - Progress: " + myDownload.getProgress().getBytesTransfered());
try {
// Do work while we wait for our upload to complete...
Thread.sleep(500);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
} catch(Exception e){
e.printStackTrace();
}
}
This was adapted from the TransferManager class example for multiple upload. There are well over a 100,000 objects in this bucket. Any help would be great.
Please use the list() method to get a list of your files, then use the get() method to get each file.
class S3 extends AmazonS3Client {
final String bucket;
S3(String u, String p, String Bucket) {
super(new BasicAWSCredentials(u, p));
bucket = Bucket;
}
String get(String k) {
try {
final S3Object f = getObject(bucket, k);
final BufferedInputStream i = new BufferedInputStream(f.getObjectContent());
final StringBuilder s = new StringBuilder();
final byte[] b = new byte[1024];
for (int n = i.read(b); n != -1; n = i.read(b)) {
s.append(new String(b, 0, n));
}
return s.toString();
} catch (Exception e) {
log("Cannot get " + bucket + "/" + k + " from S3 because " + e);
}
return null;
}
String[] list(String d) {
try {
final ObjectListing l = listObjects(bucket, d);
final List<S3ObjectSummary> L = l.getObjectSummaries();
final int n = L.size();
final String[] s = new String[n];
for (int i = 0; i < n; ++i) {
final S3ObjectSummary k = L.get(i);
s[i] = k.getKey();
}
return s;
} catch (Exception e) {
log("Cannot list " + bucket + "/" + d + " on S3 because " + e);
}
return new String[]{};
}
}
TransferManager internally uses countdownlatch which makes me believe is does concurrent download (which seems the right way to do it). It makes sense to use it than get one file after other sequentially?

Categories