I have to create a file named Lab13.txt. In the file I have 10 numbers. I import the 10 numbers and have to Multiply all the numbers from Lab13.txt by 10 and save all the new numbers a new file named Lab13_scale.txt. so if the number 10 is in lab13.txt it prints 100 to Lab13_scale.txt. Here is what
I have:
import java.io.*;
import java.util.Scanner;
public class lab13 {
public static void main(String[] args) throws IOException{
File temp = new File("Lab13.txt");
Scanner file= new Scanner(temp);
PrintWriter writer = new PrintWriter("Lab13_scale.txt", "UTF-8");
writer.println("");
writer.close();
}
}
How do I multiply the numbers by 10 and export it to the new file?
This code is simple as this:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Lab13 {
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(new File("Lab13.txt"));
PrintWriter print = new PrintWriter(new File("Lab13_scale.txt"));
while(scan.hasNext()){
print.write(10 * scan.nextInt()+"\n");
}
print.close();
scan.close();
}
}
If the numbers are separated by spaces, use
file.nextInt();
Full Code:
int[] nums = new int[10];
for(int i = 0; i < 10; i++){
nums[i] = file.nextInt();
nums[i] *= 10;
}
after writer.println("");
for(int i = 0; i < 10; i++){
writer.println(nums[i]);
}
I'll give you a different approach. I have wrote this from memory, let me know if you have any errors. I assumed the numbers are one on each line.
public static void main(String[] args)
{
String toWrite = "";
try{
String line;
BufferedReader reader = new BufferedReader(new FileReader("Lab13.txt"));
while((line = reader.readLine())!=null){
int x = Integer.parseInt(line);
toWrite += (x*10) + "\n";
}
File output = new File("lab13_scale.txt");
if(!output.exists()) output.createNewFile();
FileWriter writer = new FileWriter(output.getAbsoluteFile());
BufferedWriter bWriter= new BufferedWriter(writer);
bWriter.write(toWrite);
bWriter.close();
}catch(Exception e){}
}
Related
In a file of randomly generated passwords my goal is to ask for a password, check the 'codes.txt' file to see if it exists, say 'LOGIN COMPLETE' for 5 seconds, delete the password, then close the files. When I reach the while loop I nothing works the way I need it to. It has all kinds of different results in various situation, none of which I can understand. I haven't even figured out how to delete the stuff on the console after 5 seconds have passed printing 'LOGIN COMPLETE'. If anybody could help me right now I would really appreciate it. My code is located below.
package password;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import java.util.Scanner;
public class Password {
public void creator() throws IOException {
FileWriter fw = new FileWriter(new File("codes.txt"));
PrintWriter out = new PrintWriter(fw);
char[] chars = "abcdefghijklmnopqrstuvwxyz1234567890".toCharArray();
Random random = new Random();
for (int x = 0; x < 51; x++){
String word = "";
for (int i = 0; i <= 10; i++) {
char c = chars[random.nextInt(chars.length)];
word+=c;
}
out.println(word);
}
fw.close();
}
public void readit() throws FileNotFoundException, InterruptedException {
File file = new File("codes.txt");
Scanner input = new Scanner(file);
//prints each line in the file
while (input.hasNextLine()) {
String line = input.nextLine();
System.out.println(line);
}
Thread.sleep(10000);
input.close();
}
public void checkit() throws FileNotFoundException, IOException, InterruptedException {
File checkFile = new File("codes.txt");
File tempFile = new File("tempFile.txt");
Scanner input = new Scanner(System.in);
Scanner reader = new Scanner(checkFile);
FileWriter fw = new FileWriter(tempFile);
PrintWriter out = new PrintWriter(fw);
System.out.println("What is the password?");
String word = input.nextLine();
while(reader.hasNextLine()) {
String line = input.nextLine();
if(line.equals(word)){
System.out.println("LOGIN COMPLETE");
Thread.sleep(5000);
} else {
out.println(line);
}
}
reader.close();
fw.close();
checkFile.delete();
tempFile.renameTo(checkFile);
}
}
The main file is below.
package password;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException, FileNotFoundException, InterruptedException {
Password pass = new Password();
pass.creator();
pass.readit();
pass.checkit();
}
}
I am a beginner at java so in order for me to understand the code please use simple beginners code.
In the end I've decided there isn't really a need to clear the console screen in Netbeans, and I'll just leave it as is. I do want to give the solution I got in the end for those confused on what I wanted and for anyone who might have the same problems as I did.
package password;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import java.util.Scanner;
public class Password {
//Makes 50 random passwords(ten characters using letters and numbers)
public void creator() throws IOException {
FileWriter fw = new FileWriter(new File("codes.txt"));
PrintWriter out = new PrintWriter(fw);
char[] chars = "abcdefghijklmnopqrstuvwxyz1234567890".toCharArray();
Random random = new Random();
for (int x = 0; x < 51; x++){
String word = "";
for (int i = 0; i <= 10; i++) {
char c = chars[random.nextInt(chars.length)];
word+=c;
}
out.println(word);
}
fw.close();
}
//prints passwords for 10 seconds
public void readit() throws FileNotFoundException, InterruptedException {
File file = new File("codes.txt");
Scanner input = new Scanner(file);
//prints each line in the file
while (input.hasNextLine()) {
String line = input.nextLine();
System.out.println(line);
}
Thread.sleep(10000);
input.close();
}
//asks for password and if it's correct then states LOGIN COMPLETE and then adds exceptions to a temporary file then readds to main file then closes
public void checkit() throws FileNotFoundException, IOException, InterruptedException {
File file = new File("codes.txt");
FileWriter fw = new FileWriter(new File("code.txt"));
PrintWriter out = new PrintWriter(fw);
Scanner reader = new Scanner(file);
Scanner input = new Scanner(System.in);
System.out.println("Enter a password");
String word = input.nextLine();
//prints each line in the file
while (reader.hasNextLine()) {
String line = reader.nextLine();
if (line.equals(word)) {
System.out.println("LOGIN COMPLETE");
Thread.sleep(5000);
} else {
out.println(line);
}
}
reader.close();
fw.close();
File file2 = new File("code.txt");
Scanner reader2 = new Scanner(file2);
FileWriter fw2 = new FileWriter(new File("codes.txt"));
PrintWriter out2 = new PrintWriter(fw2);
while (reader2.hasNextLine()) {
String line = reader2.nextLine();
out2.println(line);
}
file2.delete();
fw2.close();
System.exit(0);
}
}
Main File Below:
package password;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException, FileNotFoundException, InterruptedException {
Password pass = new Password();
pass.creator();
pass.readit();
pass.checkit();
}
}
import java.awt.Graphics;
import java.awt.List;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundEsxception;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class Benford {
static Object i = null;
static ArrayList<String> list = new ArrayList<String>();
private static String data;
public static void BenfordPercents() {
int one = 0;
int two = 0;
int three = 0;
int four = 0;
int five = 0;
int six = 0;
int seven = 0;
int eight = 0;
int nine = 0;
return;
}
public static void main(String[] args) throws IOException {
DrawingPanel g = new DrawingPanel(500, 500);
Graphics brush = g.getGraphics();
String popData = null;
readCount(popData);
BenfordPercents();
}
public static void readCount(String popdata) throws IOException {
System.out.println("Please make sure the data file is name popData.txt");
System.out.println("We are loading popData.txt...");
Scanner console = new Scanner(System.in);
// Scanner console = new Scanner((new File("popData.txt")));
try {
i = new FileInputStream("popData.txt");
} catch (FileNotFoundException e) {
System.out.println("We cannot locate popData.txt");
System.out.println("Please make sure popData.txt is in the same location" + " as your code file!");
return;
}
System.out.println("popData.txt has loaded!");
System.out.println("");
System.out.println("Please press enter to show data!");
data = console.nextLine();
File file = new File(popdata + ".txt");
FileInputStream fis = new FileInputStream("popdata.txt");
byte[] flush = new byte[1024];
int length = 0;
while ((length = fis.read(flush)) != -1) {
list.add(new String(flush));
// System.out.println(new String(flush));
// System.out.println(list.toString());
}
// Scanner x = new Scanner((new File("popData.txt")));
// while(x.hasNext()){
// list.add(x.next());
// }
fis.close();
}
}
I have a text document with all the numbers of populiation from this link here:
https://en.wikipedia.org/wiki/List_of_countries_and_dependencies_by_population
The text document looks like this:
China 1369480000
India 1270250000
United 320865000
Indonesia 255461700
Brazil 204215000
Pakistan 189607000
..etc
..etc
the list is pretty long.
and when I try to store all of these numbers into an array list and I try to print the array list size it just returns 4?
If you want a list-entry for each line, you should prefer a BufferedReader.
FileInputStream fis = new FileInputStream("popdata.txt")
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
while((String line = br.readLine()) !=null) {
list.add(line);
}
The size of 4 is only the size of your arraylist - each element of your array list was build from an byte-array with a length of 1024. This means that your list either contains about 3K until 4K of data.
I want to insert random numbers into files and read those randoms numbers and store into array in java.
Please review the following piece of code,
import java.io.*;
import java.util.*;
public class sort implements Serializable
{
public static void main(String args[]) throws Exception
{
int[] al;
Random rand=new Random();
Scanner sc=new Scanner(System.in);
File fi=new File("sort.txt");
fi.createNewFile();
FileOutputStream fs=new FileOutputStream(fi);
ObjectOutputStream os=new ObjectOutputStream(fs);
System.out.println("enter how many numbers you need to sort");
int n=sc.nextInt();
al=new int[n];
for(int k=0;k<al.length;k++)
os.write(rand.nextInt(10));
FileInputStream fs1=new FileInputStream("./sort.txt");
ObjectInputStream ois=new ObjectInputStream(fs1);
ois.read();
/* i need to use this file and retrieve the randoms numbers
* from the file and store those numbers from the file and need to sort */
}
}
You might need this:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.Serializable;
import java.util.Random;
import java.util.Scanner;
public class Sort implements Serializable {
private static final long serialVersionUID = 1L;
private static final File file = new File("sort.txt");
public static void main(String args[]) throws Exception {
Random rand = new Random();
Scanner sc = new Scanner(System.in);
String sCurrentLine;
String[] array = null;
if (!file.exists()) {
file.createNewFile();
}
System.out.println("enter how many numbers you need to sort");
int n = sc.nextInt();
int[] al = new int[n];
try (FileWriter fw = new FileWriter(file);) {
for (int k = 0; k < al.length; k++) {
fw.write(new Integer(rand.nextInt(10)).toString());
}
}
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
while ((sCurrentLine = br.readLine()) != null) {
array = sCurrentLine.toString().split("");
}
for (int counter = 0; counter < array.length; counter++) {
System.out.println(array[counter]);
}
}
sc.close();
}
}
If you want keep your code.. you can read the values like this:
write:
...
for (int k = 0; k < al.length; k++) {
os.writeInt(rand.nextInt());
}
os.close();
...
read:
FileInputStream fs1 = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fs1);
int[] in = new int[n];
for (int k = 0; k < al.length; k++) {
in[k] = ois.readInt();
//System.out.println(in[k]);
}
Can anyone show me a basic guideline for how to do this sort of thing? Would you use an Array or an ArrayList, and why? Anything else I've found online is too complicated to understand for my level of experience with Java. The file is a simple text file with seven decimal values per line, and contains three lines. Here is what I have so far and am just testing it to see if I'm doing the ArrayList properly. It keeps printing an empty ArrayList that is just two brackets.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class SalesAnalysis
{
public static void main (String[] args) throws FileNotFoundException
{
Scanner salesDataFile = new Scanner(new File("SalesData.txt"));
ArrayList<Double> salesData = new ArrayList<Double>();
while(salesDataFile.hasNextDouble())
{
salesData.add(salesDataFile.nextDouble());
}
salesDataFile.close();
System.out.println(salesData);
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class SalesAnalysis
{
public static void main (String[] args) throws FileNotFoundException
{
Scanner salesDataFile = new Scanner(new File("SalesData.txt"));
ArrayList<Double> salesData = new ArrayList<Double>();
while(salesDataFile.hasNextLine()){
String line = salesDataFile.nextLine();
Scanner scanner = new Scanner(line);
scanner.useDelimiter(",");
while(scanner.hasNextDouble()){
salesData.add(scanner.nextDouble());
}
scanner.close();
}
salesDataFile.close();
System.out.println(salesData);
}
}
Read lines from file, then for each file get doubles using Scanner.
And for per line basis, you can just create Lists for every line, like:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class SalesAnalysis
{
public static void main (String[] args) throws FileNotFoundException
{
Scanner salesDataFile = new Scanner(new File("SalesData.txt"));
while(salesDataFile.hasNextLine()){
String line = salesDataFile.nextLine();
ArrayList<Double> salesData = new ArrayList<Double>();
Scanner scanner = new Scanner(line);
scanner.useDelimiter(",");
while(scanner.hasNextDouble()){
salesData.add(scanner.nextDouble());
}
scanner.close();
System.out.println(salesData);
}
salesDataFile.close();
}
}
As you are getting per line values inside first while() loop, you can do whatever with line.
// number of values in file
int totalNumValues = 0;
// total sum
double totalSum = 0;
while(salesDataFile.hasNextLine()){
String line = salesDataFile.nextLine();
ArrayList<Double> salesData = new ArrayList<Double>();
// total values in this line
int numValuesInLine = 0;
// sum in this line
double sumLine = 0;
Scanner scanner = new Scanner(line);
scanner.useDelimiter(",");
while(scanner.hasNextDouble()){
double value = scanner.nextDouble();
sumLine = sumLine + value;
numValuesInLine++;
totalNumValues++;
totalSum = totalSum + value;
}
scanner.close();
System.out.println(salesData);
}
I'd do something like this:
Scanner salesDataFile = new Scanner(new File("SalesData.txt"));
ArrayList<ArrayList< double > > salesData = new ArrayList<>();
while(salesDataFile.hasNextLine() )
{
String stringOfNumbers[] = salesDataFile.nextLine().split(",");
ArrayList< double > aux = new ArrayList<>( stringOfNumbers.length );
for( int i = 0; i < stringOfNumbers.length; ++i )
aux.get(i) = Double.parseDouble( stringOfNumbers[i] );
//... Perform your row calculations ...
salesData.add( aux );
}
salesDataFile.close();
System.out.println(salesData);
As #Justin Jasmann said, you have comma separated values, so technically they are more than just double values, why not read them as String and then parse them using Double.parseDouble(String s) after you have your comma separatad value by using string.split(","); on every line.
This is what you are looking for,
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class FileRead {
public static void main(String args[])
{
try{
// Open the file that is the first
FileInputStream fstream = new FileInputStream("textfile.txt");
// Use DataInputStream to read binary NOT text.
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
List<Double> saleNumbers= new ArrayList<Double>();
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Add number from file to list
saleNumbers.add( parseDecimal(strLine));
}
//Close the input stream
in.close();
System.out.println(saleNumbers);
}catch (Exception e){
e.printStackTrace();
}
}
public static double parseDecimal(String input) throws NullPointerException, ParseException{
if(input == null){
throw new NullPointerException();
}
input = input.trim();
NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.US);
ParsePosition parsePosition = new ParsePosition(0);
Number number = numberFormat.parse(input, parsePosition);
if(parsePosition.getIndex() != input.length()){
throw new ParseException("Invalid input", parsePosition.getIndex());
}
return number.doubleValue();
}
}
I have a text file with the following contents:
public class MyC{
public void MyMethod()
{
System.out.println("My method has been accessed");
System.out.println("hi");
}
}
I have an array num[]= {2,3,4}; which contains the line numbers to be completely replaced with the strings from this array
String[] VALUES = new String[] {"AB","BC","CD"};
That is line 2 will be replaced with AB, line 3 with BD and ine 4 with CD.
Lines which are not in the num[]array have to be written to a new file along with the changes made.
I have this so far.I tried several kind of loops but still it does not work.
public class ReadFileandReplace {
/**
* #param args
*/
public static void main(String[] args) {
try {
int num[] = {3,4,5};
String[] VALUES = new String[] {"AB","BC","CD"};
int l = num.length;
FileInputStream fs= new FileInputStream("C:\\Users\\Antish\\Desktop\\Test_File.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
LineNumberReader reader = new LineNumberReader(br);
FileWriter writer1 = new FileWriter("C:\\Users\\Antish\\Desktop\\Test_File1.txt");
String line;
int count =0;
line = br.readLine();
count++;
while(line!=null){
System.out.println(count+": "+line);
line = br.readLine();
count++;
int i=0;
if(count==num[i]){
int j=0;;
System.out.println(count);
String newtext = line.replace(line, VALUES[j]) + System.lineSeparator();
j++;
writer1.write(newtext);
}
i++;
writer1.append(line);
}
writer1.close();
}
catch (IOException e) {
e.printStackTrace();
} finally {
}
}
}
The expected output should look like this:
public class MyC{
AB
BC
CD
Sys.out.println("hi");
}
}
When I run the code, all lines appear on the same line.
You've done almost, I've updated your code with a map. Check this
int num[] = {3, 4, 5};
String[] values = new String[]{"AB", "BC", "CD"};
HashMap<Integer,String> lineValueMap = new HashMap();
for(int i=0 ;i<num.length ; i++) {
lineValueMap.put(num[i],values[i]);
}
FileInputStream fs = new FileInputStream("test.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
FileWriter writer1 = new FileWriter("test1.txt");
int count = 1;
String line = br.readLine();
while (line != null) {
String replaceValue = lineValueMap.get(count);
if(replaceValue != null) {
writer1.write(replaceValue);
} else {
writer1.write(line);
}
writer1.write(System.getProperty("line.separator"));
line = br.readLine();
count++;
}
writer1.flush();
You're appending each line to the same string. You should add the line separator character at the end of each line as well. (You can do this robustly using System.getProperty("line.separator"))
you have not appended end line character.
writer1.append(line); is appending the data in line without endline character. Thus it is showing in one line. You might need to change it to:
writer1.append(line).append("\n");
Try This
package src;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.TimeZone;
public class MainTest {
static int i ;
public static void main(String[] arg)
{
try {
int num[] = {3,4,5};
String[] VALUES = new String[] {"AB","BC","CD"};
FileInputStream fs= new FileInputStream("C:\\Test\\ren.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
FileWriter writer1 = new FileWriter("C:\\Test\\ren1.txt");
String line;
Integer count =0;
line = br.readLine();
count++;
while(line!=null){
for(int index =0;index<num.length;index++){
if(count == num[index]){
line = VALUES[index];
}
}
writer1.write(line+System.getProperty("line.separator"));
line = br.readLine();
count++;
}
writer1.close();
}
catch (Exception e) {
e.printStackTrace();
} finally {
}
}
}