Showing posts with label files. Show all posts
Showing posts with label files. Show all posts

Manipulating .txt Files in Java

Problem:

To solve this assignment, you are supposed to know file input/output (reading from and writing to a file) and array list usage.

First, fill an input file called input.txt with 12 numbers: 4 6 8 3 1 2 3 9 8 4 3 0 (each integer on a line).

In your main method, read these items from the input file, fill them in an integer array list, and write them to an output file called output.txt after concatenating each of them with the corresponding index.

The content of the output file will be:            

                                                                            4 0
6 1
8 2
3 3
1 4
2 5
3 6
9 7
8 8
4 9
3 10
0 11

                Then, remove the item at index 6 from the array list and the print on the console (on the screen using System.out.println(..)) the size of that array list (which is supposed to be 11 now) on one line, the array list items on the next line, and the sum of the items on the last line.
                The printed output on the screen must be:     11
4 6 8 3 1 2 9 8 4 3 0

48


Solution:

/**-------------------ExerciseII.java---------------------------*/
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.Scanner;

public class ExerciseII
{
 public static void main(String[] args) throws FileNotFoundException
 {
  //Calling the input.txt file with 12 numbers from memory
  Scanner scan = new Scanner(new File("input.txt"));
  
  //Creating an array list
  ArrayList  arrayList = new ArrayList();
  
  //Filling the 12 numbers in the arrayList
  while (scan.hasNext())
   arrayList.add(scan.nextInt());  
  
  //Creating output.txt file
  Formatter input = new Formatter("output.txt");
  
  //Filling the output.txt with required content
  for (int i = 0 ; i < arrayList.size(); i++)
   input.format(arrayList.get(i) + " " + i + "%n");
  
  //Closing output.txt
  input.close();
  
  //Removing item at index 6 from the array list
  arrayList.remove(6);
  
  //Printing arrayList size
  System.out.println(arrayList.size());
  
  //Printing arrayList content
  for (int i = 0 ; i < arrayList.size();i++)
   System.out.print(arrayList.get(i) + " ");
  System.out.println();
  
  //Printing sum
  int sum = 0;
  for (int i = 0 ; i < arrayList.size();i++)
   sum += arrayList.get(i);
  System.out.println(sum);
 }
}

/**-------------------input.txt---------------------------*/
4
6
8
3
1
2
3
9
8
4
3
0
/**-----------------output.txt---------------------------*/
4 0
6 1
8 2
3 3
1 4
2 5
3 6
9 7
8 8
4 9
3 10
0 11
Read More

Manipulating a 2D array from a file in Java

Problem:

Using a scanner, you should read a 2D array from a file called "numbers.txt". The first line in the file will have two integers which are the number of rows and columns respectively. After reading the two integers, you should create a 2D array in your code that has the same number of rows and columns read. Then, you continue reading the 2D array from the file.

After reading the 2D array, you need to add the value of the previous column on the current row to the current column on the current row. (Hint: ADM] += A[i][j-1])

Finally, save your array to a file called "newNumbers.txt" using a formatter.

Output:

43
123
234
456
678

136
259
4915
61321

Solution:

import java.io.File;
import java.util.Formatter;
import java.util.Scanner;

public class ProblemC {

 public static void main(String args[]) {
  try {
   Scanner scan = new Scanner(new File("numbers.txt"));
   Formatter formatter = new Formatter(new File("newNumbers.txt"));
   
   int rows = scan.nextInt();
   int cols = scan.nextInt();
   
   int A[][] = new int[rows][cols];
   
   for (int i = 0; i < rows; i++)
    for (int j = 0; j < cols; j++)
     A[i][j] = scan.nextInt();
   
   for (int i = 0; i < rows; i++)
    for (int j = 1; j < cols; j++)
     A[i][j] += A[i][j-1];
   
   for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++)
     formatter.format("%d ", A[i][j], true);
    
    formatter.format("\n", "", true);
   }
   
   scan.close();
   formatter.close();
   
  } catch (Exception e) {
   System.err.println("File error");
  }
 }
}
Read More

Capitalize a String using FileOutputStream in Java

Problem:

Using a FilelnputStream, you should read a list of strings from a file called "strings.txt". The first line in the file will represent the number of lists. After reading the lists and storing them in a String array, you should use a FileOutputStream and save the lists to a file called "stringsUp.txt". The string should be saved in upper case.

Output:

3
The quick brown fox
Java is King
This lab is awesome

THE QUICK BROWN FOX
JAVA IS KING
THIS LAB IS AWESOME

Solution:

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

public class ProblemB {

 public static void main(String args[]) {
  try {
   Scanner scan = new Scanner(new File("strings.txt"));
   
   int n = scan.nextInt();
   scan.nextLine();
   String[] strings = new String[n];
   
   for (int i = 0; i < n; i++)
    strings[i] = scan.nextLine();
   
   scan.close();
   
   PrintWriter out = new PrintWriter(new File("stringsUp.txt"));
   
   for (int i = 0; i < n; i++) {
    out.println(strings[i].toUpperCase());
    out.flush();
   }
   
   out.close();
   
  } catch (IOException e) {
   System.err.println("Could not read from file");
  }
 }
}
Read More

Reading a text file in Java Classes

Problem:

Radio
- channels : Channel[]
- volume : int
+ Radio(channels : Channel[], volume : int)
+ setChannels(channels : Channel[]) : void
 + getChannels() : Channel[]
+ setVolume(volume : int) : void
+ getVolume() : int
+ saveChannelsToFile(filename : String) : void


Channel
 - frequency : double
 - name : String
 + Channel(frequency : double, name : String)
 + setFrequency(frequency : double) : void
 + getFrequency() : double
 + setName(name : String) : void
 + getName() : String
 + toString() : String


You have to implement the previous two classes. The class Channel has two private variables, a constructor, setters and getters, and a toString mthod. The class Radio has an array of channels and a volume.

In the tester class, you are required to read input from a file called "channels.txt" using a Scanner. The first line in the input file is the number of channels. Each additional line in the input file represents the name of the channel and its frequency.

After reading the number of channels, you need to create an array of Channels and its length would be the number of channels.

For each additional line you read, you need to create a new channel and add it to the array.

After reading the input, you should create a new Radio object an give it the read channels array as a parameter. Then, you should call the method saveChannelsToFile(String filename) to save the channels array to a file called "radio.txt" using a Formatter. 

Output:

2
MixFM 104.4
RadioOne 105.5

MixFM 104.4
RadioOne 105.5 

Solution:

/**------------------------Channel.java---------------------*/
public class Channel {
 
 private double frequency;
 private String name;
 
 public Channel(double frequency, String name) {
  this.frequency = frequency;
  this.name = name;
 }

 public double getFrequency() {
  return frequency;
 }

 public void setFrequency(double frequency) {
  this.frequency = frequency;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }
}

/**------------------------Radio.java---------------------*/
import java.io.File;
import java.util.Formatter;

public class Radio {
 
 private Channel[] channels;
 private int volume;
 
 public Radio(Channel[] channels, int volume) {
  this.channels = channels;
  this.volume = volume;
 }

 public Channel[] getChannels() {
  return channels;
 }

 public void setChannels(Channel[] channels) {
  this.channels = channels;
 }

 public int getVolume() {
  return volume;
 }

 public void setVolume(int volume) {
  this.volume = volume;
 }
 
 public void saveChannelsToFile(String filename) {
 try {
 Formatter formatter = new Formatter(new File(filename));
   
 for (int i = 0; i < channels.length; i++) {
  formatter.format("%s\n", channels[i].getName()+
                           " "+channels[i].getFrequency(), true);
   }
   
   formatter.close();
  } catch (Exception e) {
   System.err.println("Could not save file");
  }
 }
}
/**------------------------RadioTester.java---------------------*/
import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class RadioTester {
 
 public static void main(String args[]) {
  Scanner scan;
  
 try {
 scan = new Scanner(new File("channels.txt"));
   
 int numberOfChannels = scan.nextInt();
   
 Channel[] channels = new Channel[numberOfChannels];
   
 for (int i = 0; i < numberOfChannels; i++) {
  String name = scan.next();
  double frequency = scan.nextDouble();
          channels[i] = new Channel(frequency, name);
   }
   
   scan.close();
   
   Radio radio = new Radio(channels, 10);
   radio.saveChannelsToFile("radio.txt");
   
  } catch (IOException e) {
   System.err.println("Error reading file");
  }
 }
}
Read More

Copying a file with java using Input/Output Stream

Description:

The piece of code below shows you how to copy two files using Java. We're going to use basic java classes, mainly they are: FileInputStream and FileOutputStream.


Solution:

package com.javaproblems.binaryfiles;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class BinaryFileCopy {

 
 public static void main(String[] args) {
  try {
   File f1 = new File("MyPhoto.jpg");
   File f2 = new File("TrgtMyPhoto.jpg");
   
   FileInputStream in = new FileInputStream(f1);
   FileOutputStream out = new FileOutputStream(f2);
   
   byte[] buf = new byte[1024];
   int len;
   
   while ((len=in.read(buf)) > 0) {
    out.write(buf, 0, len);
   }
   
   in.close();
   out.close();
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  

 }

}

Read More

Copying a file with Java using FileUtils

Description:

The piece of code below shows you how to copy or duplicate a file using Java. To do this task, we are going to use an important library from java. 

Important tips for Eclipse users:
  • Make sure to add the file you desire to duplicate in your project. The file should be added in the directory that contains src folder and NOT in the src folder where your .java files are located.
  • Make sure to download the "commons-io-2.4.jar" library. It is available on our Downloads page. 
  • Make sure also to add this library to your project. If you don't know how, click here.
  • After you execute your code, refresh the directory and you'll see your copied file.


Solution:

package com.javaproblems.files;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

public class CopyingFiles {

 
 public static void main(String[] args) {
  try {
   File f1 = new File("SrcFile.txt");
   File f2 = new File("TrgtFile.txt");
   
   FileUtils.copyFile(f1, f2);
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

}
Read More

Downloading files from the Internet using Java

Description:

The piece of code below allows to download any file(i.e. binary file) from the internet. As you see, we're handling the exceptions properly. To download any file your desire,just replace the link in the program with a link of your choice

Solution:

package com.javaproblems.binaryfiledownload;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

public class PictureDownload {

 public static void main(String[] args) {
  URL url = null;
  InputStream is = null;
  BufferedInputStream bis = null;
  FileOutputStream fos = null;
    
  byte[] buff = null;
  int nb;
  
  try {
   //Choose your URL here
   url = new URL("http://4.bp.blogspot.com/-FiN1eeHw4pk"
  + "/UmE_3_7l00I/AAAAAAAAA_g/HRP2hP1XfTU/s1600/Untitled.png");
   
   is = url.openStream();
   bis = new BufferedInputStream(is);
   
   //1024 bytes = 1 MB
   //Our binary file is less than 1MB
   //Choose a size larger than your file
   buff = new byte[1024];
   
   //Choose the same extension of the file 
   //you're downloading
   
   fos = new FileOutputStream(new File("TrgtPhoto.png"));
   
   while((nb = bis.read(buff))>0) {
    fos.write(buff, 0, nb);
   }
  } catch (MalformedURLException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   //To not get a NullPointerException 
   //in case our objects are null
   if(bis!=null)
    try {
     bis.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   //To not get a NullPointerException 
   //in case our objects are null
   if(fos != null)
    try {
     fos.close();
    } catch (IOException e) {
     e.printStackTrace();
     e.printStackTrace();
    }
  }
 }
}
Read More

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact