suppose i want to read 1st line in one method and 2nd line in another method , then how to read? how to access file globally?
class File{
private static void createFogDevices(int userId, String appId) throws Exception{
File file = new File("/home/madhu/Desktop/data.txt");
BufferedReader reader = null;
reader = new BufferedReader(new FileReader(file));
FogDevice cloud = createFogDevice(reader.readLine());
}
private static void addMobile(int userId, String appId) throws Exception{
FogDevice mobile = createFogDevice(reader.readLine());
}
}
please help,i am getting error in reader.readLine() in addMobile method.
First of all you can pass additional parameters path, and line number.
If you use java 8. Please see the following example for small files:
private static void addMobile(int userId, String appId, String path, int lineNumb) throws Exception{
String mobile =Files.readAllLines(Paths.get(path)).get(lineNumb);
}
If you use java 7. Please see the following example:
private static void addMobile(int userId, String appId, String path, int lineNumb) throws Exception{
String infoString;
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
for (int i = 0; i < lineNumb; i++) {
br.readLine();
}
infoString = br.readLine();
}
}
If you would like to make BufferedReader and File as global variables you can use the following example:
public class File {
private static java.io.File file;
private static BufferedReader reader;
static {
try {
file = new java.io.File("/home/madhu/Desktop/data.txt");
reader = new BufferedReader(new FileReader(String.valueOf(file)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private static void createFogDevices(int userId, String appId) throws Exception {
FogDevice cloud = createFogDevice(reader.readLine());
}
private static void addMobile(int userId, String appId) throws Exception {
FogDevice mobile = createFogDevice(reader.readLine());
}
}
If you want to read from 6 to 8 lines you can use the following code:
String line;
try (Stream<String> lines = Files.lines(Paths.get("G:\\B\\1.txt"))) {
line = lines.skip(6).limit(8).collect(Collectors.joining());
}
Related
Im working on a task that requires me to read from a .csv file using stream API, go over each line and construct an object with the lines. The object class is called Planet and is:
public Planet(String name, long inhabitants, boolean stargateAvailable, boolean dhdAvailable, List<String> teamsVisited) {
}
public String getName() {
return name;
}
public long getInhabitants() {
return inhabitants;
}
public boolean isStargateAvailable() {
return stargateAvailable;
}
public boolean isDhdAvailable() {
return dhdAvailable;
}
public List<String> getTeamsVisited() {
return teamsVisited;
}
#Override
public String toString() {
return name;
}
}
So using stream API to go over each of the lines of the .cvs file i need to create objects of class Planet.
I havent made any progress at all because I really am not sure how to use stream API
public class Space {
public List<Planet> csvDataToPlanets(String filePath) {
return null;
}
try the below snippet.
File inputF = new File(inputFilePath);
InputStream inputFS = new FileInputStream(inputF);
BufferedReader br = new BufferedReader(new InputStreamReader(inputFS));
// skip the header of the csv
inputList = br.lines().skip(1).map(mapToItem).collect(Collectors.toList());
br.close();
For more information check this link
public static void main(String args[]) {
String fileName = "<Your File Path"";
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
stream.forEach(<Method to split the string based with ',' as delimiter and call Constructor using Reflection API>);
} catch (IOException e) {
e.printStackTrace();
}
}
I am having a bit of an issues trying to pass in a file read by my program and sorted accordantly. I am not used to working with files, and i ran out of ideas as to how this could be achieved.
/////////////////////////////////////// class reads file ///////////////////////////////////
import java.io.*;
public class InFileReader {
private BufferedReader inputStream = null;
private String fileLine;
private StringBuilder sb;
public String getFile(File fileRead) throws FileNotFoundException,
IOException {
inputStream = new BufferedReader(new FileReader(fileRead)); //reads files
sb = new StringBuilder();
while((fileLine = inputStream.readLine()) != null){//keep reading lines in file till there is none
sb.append(fileLine).append("\n");
}
return sb.toString(); //returns StringBuffer read values in String form
}
}
///////////////////////////////////////////////////// end of read file class ///////////////////////
public void getFile(File fileRead) throws FileNotFoundException,
IOException {
try {
String input = fileReader.getFile(fileRead.getAbsoluteFile());
HashMap<Integer, Thing.Ship> hashmap = new HashMap<>();
while (!input.isEmpty()) { // as long as there is data in the file keep looping
Scanner sc = new Scanner(input); // scan file
if (!input.startsWith("//")) { // take out "//" from directory
String type = "";
if (sc.hasNext()) { // if there are character lines get next line
type = sc.next();
}
if (type.equalsIgnoreCase("port")) { // looks for "port"
world.assignPort(new Thing.SeaPort(sc)); // assigns value to Seaport
} else if (type.equalsIgnoreCase("dock")) {
world.assignDock(new Thing.Dock(sc));
} else if (type.equalsIgnoreCase("ship")) {
Thing.Ship s = new Thing.Ship(sc);
hashmap.put(s.getIndex(), s);
world.assignShip(s);
} else if (type.equalsIgnoreCase("pship")) {
Thing.Ship s = new Thing.PassengerShip(sc);
hashmap.put(s.getIndex(), s);
world.assignShip(s);
} else if (type.equalsIgnoreCase("cship")) {
Thing.Ship s = new Thing.CargoShip(sc);
hashmap.put(s.getIndex(), s);
world.assignShip(s);
} else if (type.equalsIgnoreCase("person")) {
world.assignPerson(new Thing.Person(sc));
}
}
}
//inputOut.setText(type);
inputOut.setText(world.toString());
} catch (Exception e) {
System.out.println(e + "-----");
}
}
Here fileRead knows where to find the file to be read "C:\Users\abe\IdeaProjects\CreateSeaPortDataFile\src\text.txt"
public void getFile(File fileRead) throws FileNotFoundException,
IOException {
this is where things just fall apart:
String input = fileReader.getFile(fileRead.getAbsoluteFile());
My intent here is to pass the location of the file so that the getFile class can read it and then be sorted into the hashmap.
again i am not familiar with how to work with file, any suggestion or comment would be greatly appreciated.
thank you in advanced.
If you get a FileNotFoundException then the file was not found.
You say the filename was "C:\Users\abe\IdeaProjects\CreateSeaPortDataFile\src\text.txt".
If you type that name in the code you must escape the backslash:
"C:\\Users\\abe\\IdeaProjects\\CreateSeaPortDataFile\\src\\text.txt".
I have a problem with reading specific object from a file and saving it into ArrayList.
First I write a single customer using writeCustomer(). Then I write all records from List customerList and save them to the file. This works great.
Then I want to read the saved file so I read one line using readCustomer(). This method returns one Customer and then I want to return a list with all Clients using readData() and read it, I have nullPointerException in line list.add(readCustomer(bufferedReader));
My Class Customer has one constructor and is has an override method toString().
public class SaveCustomers {
public static void main(String[] args) throws IOException {
List<Customers> customersList = new ArrayList<>();
customersList.add(new Customers("ABC", 10));
customersList.add(new Customers("SGS", 20));
customersList.add(new Customers("FSD", 30));
try (PrintWriter out = new PrintWriter("customer.txt", "UTF-8"))
{ writeData(customersList, out); }
BufferedReader bufferedReader = new BufferedReader(new FileReader("customer.txt"));
List<Customers> newList = readData(bufferedReader);
for(Customers c: newList){
System.out.println(c);
}
}
private static void writeCustomer(PrintWriter out, Customers customers){
out.println(customers.getName()+"|"+customers.getTarrif());
}
private static void writeData(List<Customers> customersList, PrintWriter out){
for(Customers c:customersList){
writeCustomer(out, c);
}
}
public static Customers readCustomer(BufferedReader bufferedReader) throws IOException {
String line = bufferedReader.readLine();
String [] tokens = line.split("\\|");
String name = tokens[0];
int time = Integer.valueOf(tokens[1]);
return new Customers(name, time);
}
public static List<Customers> readData(BufferedReader bufferedReader) throws IOException {
List<Customers> list = new ArrayList<>();
while (bufferedReader.readLine() != null) {
list.add(readCustomer(bufferedReader));
}
return list;
}}
You are close to the solution ;)
In method :
readData(BufferedReader bufferedReader)
Just change this line
for(Customers l : list) {
to this one :
while (bufferedReader.ready()) {
I'm try to create one simple reservation system, we'll read a file, then we'll add Train, Bus, etc., then we'll writer everything to output.
import java.io.*;
import java.util.*;
public class Company
{
private static ArrayList<Bus> bus = new ArrayList<Bus>();
static int buscount = 0, traincount = 0;
public static void main (String[] args) throws IOException
{
FileParser();
}
public Company()
{
}
public static void FileParser()
{
try {
File file = new File(); //i fill this later
File file2 = new File(); // i fill this later
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(file2);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
String line;
while ((line = br.readLine()) != null)
{
String[] splitted = line.split(",");
if(splitted[0].equals("ADDBUS"))
{
bus.add(buscount) = Bus(splitted[0],splitted[1],splitted[2],splitted[3],splitted[4],splitted[5]);
}
}
}
catch (FileNotFoundException fnfe) {
}
catch (IOException ioe) {
}
}
}
I try to read the file line by line. For example one of the line is "ADDBUS,78KL311,10,140,54" I split the line for "," then i try to add every pieces of array to Bus' class' constructor but i couldn't figured it out.
My Bus Class is like `
public class Bus extends Vehicle{
private String command;
private String busName;
private String busPlate;
private String busAge;
private String busSpeed;
private String busSeat;
public Bus(String command, String busname, String busplate, String busage, String busspeed, String busseat)
{
this.command = command;
this.busName = busname;
this.busPlate = busplate;
this.busAge = busage;
this.busSpeed = busspeed;
this.busSeat = busseat;
}
public String getBusName() {
return busName;
}
public void setBusName(String busName) {
this.busName = busName;
}
public String getBusPlate() {
return busPlate;
}
public void setBusPlate(String busPlate) {
this.busPlate = busPlate;
}
public String getBusAge() {
return busAge;
}
public void setBusAge(String busAge) {
this.busAge = busAge;
}
public String getBusSpeed() {
return busSpeed;
}
public void setBusSpeed(String busSpeed) {
this.busSpeed = busSpeed;
}
public String getBusSeat() {
return busSeat;
}
public void setBusSeat(String busSeat) {
this.busSeat = busSeat;
}
public String getCommand() {
return command;
}
public void setCommand(String command) {
this.command = command;
}
}
can someone show me a way to solve this problem?
Thank you,
You are missing the keyword new to create a new instance of the class:
bus.add(new Bus(...));
You can add items to ArrayList like this
bus.add( new Bus(splitted[0],splitted[1],splitted[2],splitted[3],splitted[4],splitted[5]));
you were missing new keyword before Bus constructor call. Then you can increment the counter (or do whatever)
bus.add( new Bus(splitted[0],splitted[1],splitted[2],splitted[3],splitted[4],splitted[5]));
buscount++;
try to add new Bus(...)
bus.add( new
Bus(splitted[0],splitted[1],splitted[2],splitted[3],splitted[4],splitted[5]));
As I understand if you want to call constructor you need to call new Bus(parms).
when you say new it will call constructor of your class
when you say this() again it going to call enclosing class' constructor
if you say super() it will call super class' constructor.
if you want it into a map order by counter you can use this:
Map(Integer, Bus) busPosition = new HashMap<>();
busPosition.put(buscount, new
Bus(splitted[0],splitted[1],splitted[2],splitted[3],splitted[4],splitted[5]));
When I run junit tests on my project I receive the following error when trying to test that my project can build a url correctly. I am not sure what I am doing wrong below is the trace of the failed test run as well as the distancematrixconnection class and test class. It is producing a blank output when trying to compile the url string.
org.junit.ComparisonFailure: expected:<[http://maps.googleapis.com/maps/api/distancematrix/xml?origins=albany&destinations=albany%20in&language=en-EN&sensor=false&language=en-EN&units=imperial]> but was:<[]>
at org.junit.Assert.assertEquals(Assert.java:115)
at org.junit.Assert.assertEquals(Assert.java:144)
at edu.bsu.cs222.gascalculator.tests.GoogleUrlTests.testAlbanyNYtoAlbanyINURL(GoogleUrlTests.java:26)
public class GoogleDistanceMatrixConnection
{
String startLocation;
String endLocation;
final String urlString = "http://maps.googleapis.com/maps/api/distancematrix/xml?origins=" + startLocation +"&destinations=" + endLocation +"&language=en-EN&sensor=false&language=en-EN&units=imperial";
private static String XMLFile;
public String makeXMLFile(String start, String end) throws IOException
{
startLocation = start;
endLocation = end;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
connection.connect();
BufferedReader reader = new BufferedReader( new InputStreamReader(
connection.getInputStream()));
for(String line = reader.readLine(); line != null; line =
reader.readLine())
{
setXMLFile(line);
}
return getXMLFile();
}
// public static void main(String[] args) throws IOException{
// GoogleDistanceMatrixConnection c = new GoogleDistanceMatrixConnection();
// }
public static String getXMLFile() {
return XMLFile;
}
public static void setXMLFile(String xMLFile) {
XMLFile = xMLFile;
}
public boolean doesPageExist() {
if(XMLFile == null)
return true;
else
return false;
}
}
public class GoogleUrlTests {
private GoogleDistanceMatrixConnection urlString = new GoogleDistanceMatrixConnection();
private String generatedUrl = "";
private String actualUrl = "";
#Test
public void testAlbanyNYtoAlbanyINURL() throws IOException {
generatedUrl = urlString.makeXMLFile("albany", "albany+in");
actualUrl = "http://maps.googleapis.com/maps/api/distancematrix/xml?origins=albany&destinations=albany%20in&language=en-EN&sensor=false&language=en-EN&units=imperial";
Assert.assertEquals(actualUrl, generatedUrl);
}
#Test
public void testLosAngelesToNewYorkURL() throws IOException {
generatedUrl = urlString.makeXMLFile("losangeles", "newyork");
actualUrl = "http://maps.googleapis.com/maps/api/distancematrix/xml?origins=losangeles&destinations=newyork&language=en-EN&sensor=false&language=en-EN&units=imperial";
Assert.assertEquals(actualUrl, generatedUrl);
}
}
Comparing your test cases and your code in makeXMLFile, I'm confused of what you are really trying to do here.
If you want to pass you tests, then I think this code will do that for you. You can use URLEncoder to properly encode your URL string.
public class GoogleDistanceMatrixConnection
{
public String makeXMLFile(String start, String end) throws IOException
{
return "http://maps.googleapis.com/maps/api/distancematrix/xml?origins=" + URLEncoder.encode(start) +"&destinations=" + URLEncoder.encode(end) +"&language=en-EN&sensor=false&language=en-EN&units=imperial";
}
}
Otherwise, you need to clarify your question.