I'm trying to fill my HashMap with Strings from the text file (zadania.txt) . It's a simple text file in format like :
Q: question 1
A: answer for question 1
Q: question 2
A: answer for question 2 etc ...
Then I want to write it out on console and here the problem is . It runs , but doesn't write out anything. When I change the source file it works but I'm wondering why it doesn't work with that file ( file is ok, not broken , written in Pages and saved as a text file). Anyone can help ? Here's my code :
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
public class testClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
File file = new File("zadania.txt");
try {
Scanner skaner = new Scanner(file);
HashMap<String,String> questions = new HashMap<String,String>();
while(skaner.hasNext()){
String question = skaner.nextLine();
String answer = skaner.nextLine();
questions.put(question, answer);
}
Iterator<String> keySetIterator = questions.keySet().iterator();
while(keySetIterator.hasNext()){
String key = keySetIterator.next();
System.out.println(key + "//** " +questions.get(key));
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
If you use that path to your file File file = new File("zadania.txt");, you need to put your file zadania.txt in the root folder of project.
Or you can create folder resources put your file there and edit path to File file = new File("resources/zadania.txt");
Your code works for me. So, as Oli Charlesworth already mentioned, you should add some output in the first loop, to check that something gets inserted. If not you seem to have an empty file named zadania.txt.
Some other hints for further java programms:
Close your skaner! If you are using Java 7 you can use the try-with-resources:
try (Scanner skaner = new Scanner(file)){
//...
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Otherwise use the finally construct:
Scanner skaner = null;
try {
skaner = new Scanner(file)
//...
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(skaner != null) {
skaner.close();
}
}
Otherwise you may risk (in larger programms) to run out of file handles. It's best practice to close any resource you open.
Class names should be written (by convention) with a leading capital letter, so in your case it would be TestClass.
If you iterate over both, the key and the value of a Map use the Map.entrySet() method to get both. With large maps this is faster than iterating over the key and the call Map.get() to get the Value.
Here is another option to read your *.txt File and put it into a HashMap
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
public class App {
public static void main(String[] args) {
Map<String, String> questions = new HashMap<>();
Scanner scanner = null;
try {
scanner = new Scanner(new FileInputStream(new File("zanader.txt")));
while (scanner.hasNext()) {
String question = scanner.nextLine();
String answer = scanner.nextLine();
questions.put(question, answer);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (scanner != null) {
scanner.close();
}
}
// get an iterator
Iterator<Map.Entry<String, String>> itr = questions.entrySet().iterator();
// and go through it
while (itr.hasNext()) {
// get the entryset from your map
Map.Entry<String, String> value = itr.next();
// return only the key
String question = value.getKey();
System.out.println("Get answer by key: " + questions.get(question));
System.out.println("Question: " + value.getKey() + " - Answer: " + value.getValue());
}
}
}
I commented the interesting parts.
Patrick
Related
We have a requirement where we would like to convert an avro file which we download from our third party vendor API in our java web application. I tried going through some of the resources where all i could find was command s to execute with help of avro-tools.jar But i am looking for a way to achieve this within Java web application. Any help greatly appreciated.
You can use avro-tools to read the avro records , get Schema and records from the file
Attaching a rough draft :
I'm using JSON as intermediary ,You can modify it to any format of your choice
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.CDL;
import org.json.JSONArray;
import org.json.JSONException;
import org.apache.avro.Schema;
import org.apache.avro.Schema.Field;
import org.apache.avro.file.DataFileReader;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericDatumReader;
import org.apache.commons.io.FileUtils;
public class AvroToCSV {
public static void readAvro(File file) {
// Read Avro ,parse Schema to get field names and parse it to json
try {
GenericDatumReader<GenericData.Record> datum = new GenericDatumReader<GenericData.Record>();
DataFileReader<GenericData.Record> reader = new DataFileReader<GenericData.Record>(file, datum);
GenericData.Record record = new GenericData.Record(reader.getSchema());
Schema schema = reader.getSchema();
List<String> fieldValues = new ArrayList<>();
JSONArray jsonArray = new JSONArray();
for (Field field : schema.getFields()) {
fieldValues.add(field.name());
}
while (reader.hasNext()) {
reader.next(record);
Map<String, String> jsonFileds = new HashMap<String, String>();
for (String item : fieldValues) {
System.out.println(item);
jsonFileds.put(item, record.get(item).toString());
}
jsonArray.put(jsonFileds);
}
System.out.println(jsonArray.toString());
reader.close();
jsonToCSV(jsonArray);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void jsonToCSV(JSONArray json) {
File file = new File("avroToJson.csv");
String csv;
try {
csv = CDL.toString(json);
FileUtils.writeStringToFile(file, csv);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
File f = new File("test.avro");
readAvro(f);
}
}
Hopefully this is simple.
I am using pdfbox to extract images from a pdf. I want to write the images to a folder. I don't seem to get any output (the folder has read and write privileges).
I am probably not writing the output stream properly I think.
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.graphics.xobject.PDXObjectImage;
public final class JavaImgExtactor
{
public static void main(String[] args) throws IOException{
Stuff();
}
#SuppressWarnings("resource")
public static void Stuff() throws IOException{
File inFile = new File("/Users/sebastianzeki/Documents/Images Captured with Proc Data Audit.pdf");
PDDocument document = new PDDocument();
//document=null;
try {
document = PDDocument.load(inFile);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
List pages = document.getDocumentCatalog().getAllPages();
Iterator iter = pages.iterator();
while (iter.hasNext()) {
PDPage page = (PDPage) iter.next();
System.out.println("page"+page);
PDResources resources = page.getResources();
Map pageImages = resources.getImages();
if (pageImages != null) {
Iterator imageIter = pageImages.keySet().iterator();
System.out.println("Success"+imageIter);
while (imageIter.hasNext()) {
String key = (String) imageIter.next();
PDXObjectImage image = (PDXObjectImage) pageImages.get(key);
FileOutputStream out = new FileOutputStream("/Users/sebastianzeki/Documents/ImgPDF.jpg");
try {
image.write2OutputStream(out);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
You are not closing the output stream, and the file name is always the same.
try (FileOutputStream out = new FileOutputStream("/Users/sebastianzeki/Documents/ImgPDF" + key + ".jpg") {
write2OutputStream(out);
} (Exception e) {
printStackTrace();
}
try-with-resources will automatically close out. Not sure whether key is usable as file name part.
image.write2OutputStream(out); writes the bytes from the image object to the out FileOutputStream object but it doesn't flush the buffer of out .
Add it should do the job :
out.flush();
I am new to java, but not coding. I am trying to figure out java because it's part of my class this term and I am having a really hard problem grasping the idea of it and implementing things in java.
my problem Is that I am not sure if I am correctly using the arraylist to grab data from the scan of the file and input it into a arraylist to sort and print at a later time. I am just having issues picking up on java any help would be great since I am new to java.
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.ArrayList;
import java.util.*;
public class MissionCount
{
private static ArrayList<String> list = new ArrayList<String>();
// returns an InputStream that gets data from the named file
private static InputStream getFileInputStream(String fileName) throws Exception {
InputStream inputStream;
try {
inputStream = new FileInputStream(new File(fileName));
}
catch (FileNotFoundException e) { // no file with this name exists
inputStream = null;
throw new Exception("unable to open the file -- " + e.getMessage());
}
return inputStream;
}
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("USage: MissionCount <datafile>");
//System.exit(1);
}
try {
System.out.printf("CS261 - MissionCount - Chad Dreher%n%n");
int crewcount = 0;
int misscount = 0;
InputStream log = getFileInputStream(args[0]);
Scanner sc = new Scanner(log);
sc.useDelimiter(Pattern.compile(",|\n"));
while (sc.hasNext()) {
String crewMember = sc.next();
list.add(crewMember);
String mission = sc.next();
list.add(mission);
}
sc.close();
// Add code to print the report here
}catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
InputStream log = getFileInputStream(args[0]);
Change that line to as follows :-
File log = new File(args[0])
that should work!
I need to make my program read a file, then take the numbers in the string and sort them into an array. I can get my program to read the file and put it to a string, but that's where I'm stuck. All the numbers are on different lines in the file, but appear as one long number in the string. This is what I have so far:
public static void main(String[] args) {
String ipt1;
Scanner fileInput;
File inFile = new File("input1.dat");
try {
fileInput = new Scanner(inFile);
//Reads file contents
while (fileInput.hasNext()) {
ipt1 = fileInput.next();
System.out.print(ipt1);
}
fileInput.close();
}
catch (FileNotFoundException e) {
System.out.println(e);
}
}
I recommend reading the values in as numeric types using fileInput.nextInt() or whatever type you want them, putting them in an array and using a built in sort like Arrays.sort. Unless I'm missing a more subtle point about the question.
If your task is just to get input from some file and you're sure the file has integers, use an ArrayList.
import java.util.*;
Scanner fileInput;
ArrayList<Double>ipt1 = new ArrayList<Double>();
File inFile = new File("input1.dat");
try {
fileInput = new Scanner(inFile);
//Reads file contents
while (fileInput.hasNext()){
ipt1.add(fileInput.nextDouble()); //Adds the next Double to the ArrayList
System.out.print(ipt1.get(ipt1.size()-1)); //Prints out what you just got.
}
fileInput.close();
}
catch (FileNotFoundException e){
System.out.println(e);
}
//Sorting time
//This uses the built-in Array sorting.
Collections.sort(ipt1);
However, if you DO need to come up with a simple array in the end, but CAN use ArrayLists, you can add the following:
Double actualResult[] = new Double[ipt1.size()]; //Declare array
for(int i = 0; i < ipt1.size(); ++i){
actualResult[i] = ipt1.get(i);
}
Arrays.sort(actualResult[]);
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class SortNumberFromFile {
public static void main(String[] args) throws IOException {
BufferedReader br = null;
try {
System.out.println("Started at " + LocalDateTime.now());
br = new BufferedReader(new FileReader("/folder/fileName.csv"));//Read data from file named /folder/fileName.csv
List<Long> collect = br.lines().mapToLong(a -> Long.parseLong(a)).boxed().collect(Collectors.toList());//Collect all read data in list object
Collections.sort(collect);//Sort the data
writeRecordsToFile(collect, "/folder/fileName.txt");//Write sorted data to file named /folder/fileName.txt
System.out.println("Ended at " + LocalDateTime.now());
}
finally {
br.close();
}
}
public static <T> void writeRecordsToFile(Collection<? extends T> items, String filePath) {
BufferedWriter writer = null;
File file = new File(filePath);
try {
if(!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
writer = new BufferedWriter(new FileWriter(filePath, true));
if(items != null && items.size() > 0) {
for(T eachItem : items) {
if(eachItem != null) {
writer.write(eachItem.toString());
writer.newLine();
}
}
}
} catch (IOException ex) {
}finally {
try {
writer.close();
} catch (IOException e) {
}
}
}
}
I would like to run a Dos program from a web server. The Dos program has to be run interactively as the user interface is via a series of questions and answers. The answer to one question will determine the next question. I will have to use ajax on the web server, but I think I can do that.
I found one java program on Stackoverflow which seems to do something similar to what I want. However when I compile the program I get an error ie.
javac PipeRedirection.java
PipeRedirection.java:43: package InputProcess does not exist
InputProcess.Gobbler outGobbler = new InputProcess.Gobbler(p.getInputStream());
The stack overflow question url was
How can I write large output to Process getOutputStream?
The Java file was
/*
####### PipeRedirection.java
*/
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
public class PipeRedirection {
public static void main(String[] args) throws FileNotFoundException {
if(args.length < 2) {
System.err.println("Need at least two arguments");
System.exit(1);
}
try {
String input = null;
for(int i = 0; i < args.length; i++) {
String[] commandList = args[i].split(" ");
ProcessBuilder pb = new ProcessBuilder(commandList);
//pb.redirectErrorStream(true);
Process p = pb.start();
if(input != null) {
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(p.getOutputStream())), true);
writer.println(input);
writer.flush();
writer.close();
}
InputProcess.Gobbler outGobbler = new InputProcess.Gobbler(p.getInputStream());
InputProcess.Gobbler errGobbler = new InputProcess.Gobbler(p.getErrorStream());
Thread outThread = new Thread(outGobbler);
Thread errThread = new Thread(errGobbler);
outThread.start();
errThread.start();
outThread.join();
errThread.join();
int exitVal = p.waitFor();
System.out.println("\n****************************");
System.out.println("Command: " + args[i]);
System.out.println("Exit Value = " + exitVal);
List<String> output = outGobbler.getOuput();
input = "";
for(String o: output) {
input += o;
}
}
System.out.println("Final Output:");
System.out.println(input);
} catch (IOException ioe) {
// TODO Auto-generated catch block
System.err.println(ioe.getLocalizedMessage());
ioe.printStackTrace();
} catch (InterruptedException ie) {
// TODO Auto-generated catch block
System.err.println(ie.getLocalizedMessage());
ie.printStackTrace();
}
}
public static class Gobbler implements Runnable {
private BufferedReader reader;
private List<String> output;
public Gobbler(InputStream inputStream) {
this.reader = new BufferedReader(new InputStreamReader(inputStream));
}
public void run() {
String line;
this.output = new ArrayList<String>();
try {
while((line = this.reader.readLine()) != null) {
this.output.add(line + "\n");
}
this.reader.close();
}
catch (IOException e) {
// TODO
System.err.println("ERROR: " + e.getMessage());
}
}
public List<String> getOuput() {
return this.output;
}
}
}
Does anyone know why I get the compile error? Can I substitute some other code for InputProcess?
Thanks for any help
Peter
I think it's pretty obvious that you're missing parts to this code. A package named InputProcess which has a class called Gobbler was not included in the OP's post. Probably because it was not relevant to their question.
The error message essentially says that it can not find this package/code that it is looking for.
What this class does exactly, only the OP can tell you. At its most basic, though, it appears to read from an InputStream and convert it to a List<String>. I would read up on Java IO and try to replicate similar functionality.
Edit:
Looks like the Gobbler class is indeed included in the example above. Remove the InputProcess package name from your code (or put the Gobbler class in an InputProcess package) and you should be good to go.