public static void main(String[] args) throws IOException{
try {
List<String> line = Files.readAllLines(Paths.get("/home/madhu/Desktop/demo.txt"));
Scanner scanner = new Scanner((Readable) line);
List<FogDevice> fogdevices =new ArrayList<FogDevice>();
while(scanner.hasNextLine()){
String data[]=scanner.nextLine().split(" ");
System.out.println(data);
fogdevices.add(createFogDevice(data[0],Boolean.parseBoolean(data[1]),Long.parseLong(data[2]),Integer.parseInt(data[3]),Double.parseDouble(data[4]),Double.parseDouble(data[5]),Double.parseDouble(data[6])));
}
scanner.close();
System.out.println(fogdevices);
}catch (NumberFormatException e) {
System.out.println(e);
}
}
private static FogDevice createFogDevice(String name2, boolean x2,long mips2,int ram2, double ratepermips2,
double busypower2, double idlepower2) {
--------
---------some activity-----
return fogdevice ;
}
Format of demo.txt :
FD1,true,102400,4000,0.01,103,83.25
FD0,false,102400,4000,0.01,103,83.25
i want output in the below form by using createfogdevice function.
fogdevice1 : FD1,true,102400,4000,0.01,103,83.25
fogdevice2 : FD0,false,102400,4000,0.01,103,83.25
The problem is that you're confusing and mixing two different approaches to reading a file line-by-line. You started off using the nio method readAllLines, and then tried to switch gears to a Scanner and nextLine().
Either approach will work, you just have to pick one and stick with it.
So, if you like like readAllLines:
try {
List<String> line = Files.readAllLines(Paths.get("/home/madhu/Desktop/demo.txt"));
List<FogDevices> fogdevices = new ArrayList<>();
for (String l : line) {
String data[] = l.split("\\s*,\\s*");
System.out.println(data);
fogdevices.add(
createFogDevice(
data[0],
Boolean.parseBoolean(data[1]),
Long.parseLong(data[2]),
Integer.parseInt(data[3]),
Double.parseDouble(data[4]),
Double.parseDouble(data[5]),
Double.parseDouble(data[6])
));
}
System.out.println(fogdevices);
} catch (NumberFormatException e) {
System.out.println(e);
}
Or if you prefer to go with Scanner:
try {
Scanner scanner = new Scanner(Paths.get("/home/madhu/Desktop/demo.txt"));
List<FogDevices> fogdevices = new ArrayList<FogDevices>();
while (scanner.hasNextLine()) {
String data[] = scanner.nextLine().split("\\s*,\\s*");
System.out.println(data);
fogdevices.add(
createFogDevice(
data[0],
Boolean.parseBoolean(data[1]),
Long.parseLong(data[2]),
Integer.parseInt(data[3]),
Double.parseDouble(data[4]),
Double.parseDouble(data[5]),
Double.parseDouble(data[6])
));
}
scanner.close();
System.out.println(fogdevices);
} catch (NumberFormatException e) {
System.out.println(e);
}
Related
I have a textfile that has hundreds of doubles, all separated by commas and I am trying to write a method to get each of the doubles into an array list of doubles. Here's my code:
public void ReadFile(String inputfile) throws FileNotFoundException {
File myFile = new File(inputfile);
Scanner sc = new Scanner(myFile);
try {
while (sc.hasNextDouble()) {
int i = 0;
arraylist.add(sc.useDelimiter(","));
i++;
}
} catch (Exception e) {
System.out.println("Error");
}
sc.close();
}
The trouble I am having is with the line arraylist.add(sc.useDelimiter(","))'
I get an error saying "The method add(Double) in the type ArrayList is not applicable for the arguments (Scanner)". I am unsure of what to do to fix this. Any help?
As #Hovercraft said you need to set the delimiter once and move it up to where you initialized the scanner. It should look like this:
public void ReadFile(String inputfile) throws FileNotFoundException {
File myFile = new File(inputfile);
Scanner sc = new Scanner(myFile);
List<double> doublelist = new ArrayList<Double>();
//this is where you set the delimiter
sc.useDelimiter(",")
try {
while (sc.hasNextDouble()) {
doublelist.add(sc.nextDouble());
}
} catch (Exception e) {
System.out.println("Error");
}
sc.close();
}
You have to move the useDelimiter outside of loop. You have to also call nextDouble to iterate the numbers in the file.
public static List<Double> readFile(String inputfile) throws FileNotFoundException{
List<Double> arraylist = new ArrayList<Double>();
File myFile = new File(inputfile);
Scanner sc = new Scanner(myFile);
sc.useDelimiter(",");
try {
while (sc.hasNextDouble()) {
Double number = sc.nextDouble();
arraylist.add(number);
}
}catch (Exception e) {
System.out.println("Error");
}
sc.close();
return arraylist;
}
Also please follow proper naming convention in Java. A method name should start with a lower case letter.
I'm trying to create a List by reading a txt file. For example:
12345; Mary Jane ; 20
12365; Annabelle Gibson; NA
Each line contains: number; name; Grade (grade can be a String or a int)
I created the following method;
public static List <Pauta>leFicheiro( String nomeF) throws FileNotFoundException{
List<Pauta> pautaT = new LinkedList<Pauta>();
try {
Scanner s = new Scanner(new File (nomeF));
try{
List<Pauta> pautaS =pautaT;
while ( s.hasNextLine()){
String line = s.nextLine();
String tokens[]= line.split(";");
if(s.hasNextInt()) {
System.out.println ("next int = " + s.nextInt());
}
pautaS.add(new Pauta (s.nextInt(), tokens[1],tokens[2]);
}
pautaT = pautaS;
}
finally {
s.close();
}
}
catch (FileNotFoundException e){
e.printStackTrace();
}
catch (ParseException e){
e.printStackTrace();
}
return pautaT;
}
Pauta is a class that receives as arguments ( int, String, String), I thought Grade as a String to make it more simple, but if you have ideas on how to still create a List (main goal) by having it String or int I would be thankful.
Now the problem is: The part s.nextInt() is returning error : InputMismatchException
So I put this following code:
catch (InputMismatchException e) {
System.out.print(e.getMessage());}
which says it returns a null.
How can I solve this?
Instead of using the s.nextInt(), parse the first token to an Integer.
See the example below.
public static void main(String... args) throws FileNotFoundException {
List<Pauta> pautaT = new LinkedList<Pauta>();
try {
Scanner s = new Scanner(new File("test.txt"));
try{
List<Pauta> pautaS =pautaT;
while ( s.hasNextLine()){
String line = s.nextLine();
String tokens[]= line.split(";");
pautaS.add(new Pauta (Integer.parseInt(tokens[0]), tokens[1],tokens[2]));
}
pautaT = pautaS;
}
finally {
s.close();
}
}
catch (FileNotFoundException e){
e.printStackTrace();
}
}
This results in the list to be populated.
Yo may use StringTokenizer and save each token of the same line into a variable and then use them as you want.
I'm trying to read a text file to get a version number but for some reason no matter what I put in the text file it always returns 0 (zero).
The text file is called version.txt and it contains no spaces or letters, just 1 character that is a number. I need it to return that number. Any ideas on why this doesn't work?
static int i;
public static void main(String[] args) {
String strFilePath = "/version.txt";
try
{
FileInputStream fin = new FileInputStream(strFilePath);
DataInputStream din = new DataInputStream(fin);
i = din.readInt();
System.out.println("int : " + i);
din.close();
}
catch(FileNotFoundException fe)
{
System.out.println("FileNotFoundException : " + fe);
}
catch(IOException ioe)
{
System.out.println("IOException : " + ioe);
}
}
private final int VERSION = i;
Here is the default solution that i use whenever i require to read a text file.
public static ArrayList<String> readData(String fileName) throws Exception
{
ArrayList<String> data = new ArrayList<String>();
BufferedReader in = new BufferedReader(new FileReader(fileName));
String temp = in.readLine();
while (temp != null)
{
data.add(temp);
temp = in.readLine();
}
in.close();
return data;
}
Pass the file name to readData method. You can then use for loop to read the only line in the arraylist, and can use the same loop to read multiple lines from different file...I mean do whatever you like with the arraylist.
Please don't use a DataInputStream
Per the linked Javadoc, it lets an application read primitive Java data types from an underlying input stream in a machine-independent way. An application uses a data output stream to write data that can later be read by a data input stream.
You want to read a File (not data from a data output stream).
Please do use try-with-resources
And since you seem to want an ascii integer, I'd suggest you use a Scanner.
public static void main(String[] args) {
String strFilePath = "/version.txt";
File f = new File(strFilePath);
try (Scanner scanner = new Scanner(f)) {
int i = scanner.nextInt();
System.out.println(i);
} catch (Exception e) {
e.printStackTrace();
}
}
Use an initializing block
An initializing block will be copied into the class constructor, in your example remove public static void main(String[] args), something like
private int VERSION = -1; // <-- no more zero!
{
String strFilePath = "/version.txt";
File f = new File(strFilePath);
try (Scanner scanner = new Scanner(f)) {
VERSION = scanner.nextInt(); // <-- hope it's a value
System.out.println("Version = " + VERSION);
} catch (Exception e) {
e.printStackTrace();
}
}
Extract it to a method
private final int VERSION = getVersion("/version.txt");
private static final int getVersion(String strFilePath) {
File f = new File(strFilePath);
try (Scanner scanner = new Scanner(f)) {
VERSION = scanner.nextInt(); // <-- hope it's a value
System.out.println("Version = " + VERSION);
return VERSION;
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
or even
private final int VERSION = getVersion("/version.txt");
private static final int getVersion(String strFilePath) {
File f = new File(strFilePath);
try (Scanner scanner = new Scanner(f)) {
if (scanner.hasNextInt()) {
return scanner.nextInt();
}
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
I have a list of Strings in single column. I want to make three columns from these string and then print the ouput to another file. How do I do this?
Here is what I've tried so far:
ArrayList<String> list=new ArrayList<String>();
File file = new File("f://file.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
My input data:
City
Gsk
Relocation
sripallu
here
jrajesh
gurgaon
unitech
StatisticsThreads
WizOty
LTDParsvnathK
Quotesby
newest
PMaashuktr
My expected output:
City Gsk Relocation
sripallu here jrajesh
gurgaon unitech StatisticsThreads
WizOty LTDParsvnathK Quotesby
newest PMaashuktr Loans
.
.
.
.
.
.
.
You can structured your requirement in class like Output and make a list of Output.
public class Output{
private String str1;
private String str2;
private String str3;
<geter & setter method>
}
...
ArrayList<Output> list=new ArrayList<Output>();
int i=-1; Output op =null;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();i = ++i%3;
if(i==0){
op = new Output();
op.setStr1(line);
}else if(i==1)
op.setStr2(line);
else
op.setStr3(line);
}
I took your code and modified it a little:
File file = new File("f://file.txt");
try {
Scanner scanner = new Scanner(file);
int itemsOnRow = 0;
while (scanner.hasNextLine())
{
String line = scanner.nextLine();
System.out.print (line + " ");
itemsOnRow++;
if (itemsOnRow == 3)
{
itemsOnRow = 0;
System.out.println ();
}
}
scanner.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
You should actually try to implement it next time. If you fail but post the code that you wrote, then it's easier for the people here to help you.
I have a text file that reads:
Description|SKU|Retail Price|Discount
Tassimo T46 Home Brewing System|43-0439-6|17999|0.30
Moto Precise Fit Rear Wiper Blade|0210919|799|0.0
I've got it so that I read everything, and it works perfectly, save for the fact that it reads the first line, which is a sort of legend for the .txt file, which must be ignored.
public static List<Item> read(File file) throws ApplicationException {
Scanner scanner = null;
try {
scanner = new Scanner(file);
} catch (FileNotFoundException e) {
throw new ApplicationException(e);
}
List<Item> items = new ArrayList<Item>();
try {
while (scanner.hasNext()) {
String row = scanner.nextLine();
String[] elements = row.split("\\|");
if (elements.length != 4) {
throw new ApplicationException(String.format(
"Expected 4 elements but got %d", elements.length));
}
try {
items.add(new Item(elements[0], elements[1], Integer
.valueOf(elements[2]), Float.valueOf(elements[3])));
} catch (NumberFormatException e) {
throw new ApplicationException(e);
}
}
} finally {
if (scanner != null) {
scanner.close();
}
}
return items;
}
How do I ignore the first line using the Scanner class?
Simply calling scanner.nextLine() once before any processing should do the trick.
how about calling scanner.nextLine() as outside your loop.
scanner.nextLine();//this would read the first line from the text file
while (scanner.hasNext()) {
String row = scanner.nextLine();
scanner.nextLine();
while (scanner.hasNext()) {
String row = scanner.nextLine();
....