I cant figure out how to loop through this instead of just repeating the code, bugging the hell outta me! FYI assignment has already been turned in using 5 iterations of code, just wanted to learn how to implement the string array holding file contents into a for loop for future knowledge. I have tried for a few hours but it just prints the filename, cant seem to get the file contents.
/*************************************************************************
* LinuxSys.java
*
* This program reads text from a file
**************************************************************************/
import java.util.*;
import java.io.*;
public class LinuxSys {
public static void main (String[] args) {
String systemInfo[] = new String [5];
int i = 0;
// using _ to simulate file paths to test on local cpu, as it is easier/quicker
// than logging onto server/copy pasting code into new pico file
systemInfo[0] = "_proc_sys_kernel_hostname.txt"; //local files
systemInfo[1] = "_proc_meminfo.txt"; //local files
systemInfo[2] = "_proc_version.txt"; //local files
systemInfo[3] = "_proc_sys_kernel_hostname.txt"; //local files
//systemInfo[0] = "_proc_sys_kernel_hostname.txt"; //local files
// 1st try to print server host name file
try {
BufferedReader inputStream =
new BufferedReader(new FileReader(systemInfo[i]));
String line = "blank";
while (line != null) {
if((line = inputStream.readLine()) != null) {
System.out.println(line);
i++; // increment systemInfo[] array position
} // end if
} //end while
System.out.println(); // create space
inputStream.close();
} // end try
catch(FileNotFoundException e) {
System.out.println("File was not found");
System.out.println("or could not be opened");
} //end catch
catch(IOException e) {
System.out.println("Error reading from file");
} //end catch
// 2nd try to print server memory file
{
BufferedReader inputStream =
new BufferedReader(new FileReader(systemInfo[i]));
String line = "blank";
while (line != null) {
if((line = inputStream.readLine()) != null) {
System.out.println(line);
i++; // increment systemInfo[] array position
} // end if
} //end while
System.out.println(); // create space
inputStream.close();
} // end try
catch(FileNotFoundException e) {
System.out.println("File was not found");
System.out.println("or could not be opened");
} //end catch
catch(IOException e) {
System.out.println("Error reading from file");
} //end catch
// 3rd try to print version file
try {
BufferedReader inputStream =
new BufferedReader(new FileReader(systemInfo[i]));
String line = "blank";
while (line != null) {
if((line = inputStream.readLine()) != null) {
System.out.println(line);
i++;
} // end if
} //end while
System.out.println(); // create space
inputStream.close();
} // end try
catch(FileNotFoundException e) {
System.out.println("File was not found");
System.out.println("or could not be opened");
} //end catch
catch(IOException e) {
System.out.println("Error reading from file");
} //end catch
} // end main
} // end class
for(int i=0; i < systemInfo.size; ++i)
{
// the code you want to repeat with i varying each time
}
or
int i=0;
while(i < systemInfo.size)
{
// the code you want to repeat with i varying each time
++i;
}
or
int i=0;
while(i++ < systemInfo.size)
{
// the code you want to repeat with i varying each time
}
or
int i=0;
do
{
// the code you want to repeat with i varying each time
}
while(++i < systemInfo.size)
or...
Related
I need my program to print this file line by line, waiting for the user to press enter between each one. My code keeps printing the whole excerpt. What do I need to change?
import java.io.*;
import java.util.*;
public class NoteCopier {
public static void main(String[] args) throws IOException {
System.out.println("Hello! I copy an excerpt to the screen line for line"
+ " just press enter when you want a new line!");
try {
File file = new File("excerpt.txt");
FileInputStream fis = new FileInputStream(file);
InputStreamReader inreader = new InputStreamReader(fis);
BufferedReader reader = new BufferedReader(inreader);
String line = reader.readLine();
Scanner scan = new Scanner(System.in);
while(true) {
String scanString = scan.nextLine();
if(line != null) {
if(scanString.isEmpty()){
System.out.println(line);
line = reader.readLine();
}
else {
scanString = null;
break;
}
}
}
}
catch(IOException e) {
e.printStackTrace();
}
}
}
If line is null you'll loop forever; the nested if statements.
I did it in the new Stream style, without the ubiquitous but needless Scanner on System.in.
private void dump(String file) {
Path path = Paths.get(file);
BufferedReader con = new BufferedReader(new InputStreamReader(System.in));
try (Stream<String> in = Files.lines(path, Charset.defaultCharset())) {
AtomicInteger lineCounter = new AtomicInteger();
in.forEach(line -> {
System.out.println(line);
if (lineCounter.get() == 0) {
String input = null;
try {
input = con.readLine();
} catch (IOException e) {
}
if (input == null) {
throw new IndexOutOfBoundsException();
} else if (input.equals(" ")) {
lineCounter.set(10);
}
} else {
lineCounter.decrementAndGet();
}
});
} catch (IndexOutOfBoundsException e) {
System.out.println("< Stopped.");
} catch (IOException e) {
e.printStackTrace();
}
}
With CtrlD you can exit on Windows I believe.
I have added that a line with a Space will dump the next 10 lines.
The ugly thing are the user input lines.
With java.io.Console one can ask input with a String prompt, which then can be used to print the file's line as prompt.
private void dump(String file) {
Path path = Paths.get(file);
Console con = System.console();
try (Stream<String> in = Files.lines(path, Charset.defaultCharset())) {
AtomicInteger lineCounter = new AtomicInteger();
in.forEach(line -> {
if (lineCounter.get() == 0) {
//String input = con.readLine("%s |", line);
String input = new String(con.readPassword("%s", line));
if (input == null) {
throw new IndexOutOfBoundsException();
} else if (input.equals(" ")) {
lineCounter.set(10);
}
} else {
System.out.println(line);
lineCounter.decrementAndGet();
}
});
} catch (IndexOutOfBoundsException e) {
System.out.println("< Stopped.");
} catch (IOException e) {
e.printStackTrace();
}
}
Using a prompt with the file's line, and asking a non-echoed "password" will be sufficient okay. You still need the Enter.
There is one problem: you must run this as real command line. The "console" in the IDE uses System.setIn which will cause a null Console. I simply create a .bat/.sh file. Otherwise System.out.print(line); System.out.flush(); might work on some operating system.
I'm currently working on a project and i need some help. Depending on the user input I have to read some data off some txt files. There are three ways to call the program:
java Graph [-u] -s start example_graph.txt
java Graph [-u] -a example_graph.txt
java Graph [-u] -d traffic.txt
The files i have to read depending on what the user chose are :
clrs.txt, traffic.txt, traffic_u.txt, facebook_combined_u.txt
The method I'm using to read and store the data of the file is
public void readFile() {
String txtFile = "filename.csv";
BufferedReader br = null;
String line = "";
String txtSplitBy = ",";
try {
br = new BufferedReader(new FileReader(txtFile));
while ((line = br.readLine()) != null) {
String[] dj = line.split(txtSplitBy);
int node_a = Integer.parseInt(dj[0]);
int node_b = Integer.parseInt(dj[1]);
int weight = Integer.parseInt(dj[2]);
if (node_a > adj.size()) {
for (int i = adj.size() + 1; i <= node_a; i++) {
adj.add(new HashSet<Link>());
}
}
HashSet<Link> h = adj.get(node_a);
h.add(new Link(node_b, weight));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
But this method only works if I have a specific file as input. Now that there are more than one files how can I get the file name into a String?
As pointed out in the comments, you can read arguments from the cmd line in the args area of the main method, for example:
public class SO {
public static void main(String[] args) {
for(String s : args){ //For each argument
if(s.indexOf(".") != -1){ //If contains a dot (like a file ext)
System.out.println(s); //print
}
}
}
}
When running this with:
java SO [-u] -a example_graph.txt
It wrote out the name of the file.
Hope this helps!
I have a class which can read a file, modify it an write it to another file. The characters in the output are correct , the only problem is that the lines need to have a length of 12 chars.
How can I achieve this with my existing code?(I wrote a comment where in the code I want to do this)
My input file: http://gyazo.com/13fe791d24ef86e29ab6a6e89d0af609
The current output: http://gyazo.com/cc195c1d59a9d1fe3b4f2c54e71da8eb
The output I want : http://gyazo.com/04efcbb05c5d56b6e28972feb8c43fb8
String line;
StringBuilder buf = new StringBuilder();
public void readFile(){
BufferedReader reader = null;
try {
File file = new File("C:/Users/Sybren/Desktop/Invoertestbestand1.txt");
reader = new BufferedReader(new FileReader(file));
//String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
//buf.append(line);
processInput();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
};
}
}
public void processInput(){
buf.append(line);
if (buf.length()>7){
buf.append("-");
}
/* if a * is followed by * change them to a ! */
for (int index = 0; index < buf.length(); index++) {
if (buf.charAt(index) == '*' && buf.charAt(index+1) == '*') {
buf.setCharAt(index, '!');
buf.deleteCharAt(index+1);
}
}
// get last character from stringbuilder and delete
buf.deleteCharAt(buf.length()-1);
/* start with a new line if the line length is bigger than 12 - how to do it? */
//???
}
public void writeFile() {
try {
String content = buf.toString();
File file = new File("C:/Users/Sybren/Desktop/uitvoer1.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}}
Would something along these lines help?
for (int i=13;i<buf.size();i+=13) {
buf.insert(i, '\n');
i++; // to account for the newline char just added
}
The numbers used may not be correct, either because of misunderstanding of the question or because it isn't tested.
for (int index = 0; index < buf.length(); index++) {
if (buf.charAt(index) == '*' && buf.charAt(index+1) == '*') {
buf.setCharAt(index, '!');
buf.deleteCharAt(index+1);
}
}
There will be an java.lang.ArrayIndexOutOfBoundsException at the end of the loop when you you call index+1
I have a program which reads a file I can change the content of this file and after that it's written to another file. The input file looks like this: http://gyazo.com/4ee1ade01378238e2c765e593712de7f and the output has to look like this http://gyazo.com/5a5bfd00123df9d7791a74b4e77f6c10 my current output is http://gyazo.com/87a83f4c6d48aebda3d11060ebad66c2 so how to change my code that it's starts a new line after 12 characters? Also I want to delete the last !.
public class readFile {
String line;
StringBuilder buf = new StringBuilder();
public void readFile(){
BufferedReader reader = null;
try {
File file = new File("C:/Users/Sybren/Desktop/Invoertestbestand1.txt");
reader = new BufferedReader(new FileReader(file));
//String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
//buf.append(line);
processInput();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
};
}
}
public void processInput(){
buf.append(line);
if (buf.length()>7){
buf.append("-");
//buf.append(System.getProperty("line.separator"));
}
/* start with a new line if the line length is bigger than 12 - in progress*/
/* I know this if doesn't work but how to fix it? */
if (buf.length()>12){
buf.append(System.getProperty("line.separator"));
}
/* if a * is followed by * change them to a !*/
for (int index = 0; index < buf.length(); index++) {
if (buf.charAt(index) == '*' && buf.charAt(index+1) == '*') {
buf.setCharAt(index, '!');
buf.deleteCharAt(index+1);
//buf.deleteCharAt(buf.length()-1);
}
// get last character from stringbuilder and delete
//buf.deleteCharAt(buf.length()-1);
}
}
public void writeFile() {
try {
String content = buf.toString();
File file = new File("C:/Users/Sybren/Desktop/test.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Update the code in which while reading the file you will take the decision :
int sevenCount = 0;
int fourteenCount = 0;
int data = 0;
while ((data = reader.read()) != -1) {
sevenCount++;
fourteenCount++;
if(sevenCount==7)
{
buf.append("-"); // append - at every 7th character
sevenCount = 0;
}
if(fourteenCount==14)
{
buf.append("\n"); // change line after evrry 14th character
fourteenCount = 0;
}
if(((char)data) == '*')
{
char c = '!'; //Change the code when char contain *
data = (int)c;
}
else
{
buf.append((char)data);
}
}
If you want to insert a newline in a string every 12 chars:
str = str.replaceAll(".{12}", "$0\n");
In Java, here is the code to read a file with a table of integers:
public static int[][] getDataset() {
// open data file to read n and m size parameters
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(filePath));
} catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(1);
}
// count the number of lines
int i = -1;
String line = null, firstLine = null;
do {
// read line
try {
line = br.readLine();
i++;
if (i == 0) firstLine = line;
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
} while (line != null);
// close data file
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
// check the data for emptiness
if (i == 0) {
System.out.println("The dataset is empty!");
System.exit(1);
}
// initialize n and m (at least the first line exists)
n = i; m = firstLine.split(" ").length;
firstLine = null;
// open data file to read the dataset
br = null;
try {
br = new BufferedReader(new FileReader(filePath));
} catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(1);
}
// initialize dataset
int[][] X = new int[n][m];
// process data
i = -1;
while (true) {
// read line
try {
line = br.readLine();
i++;
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
// exit point
if (line == null) break;
// convert a line (string of integers) into a dataset row
String[] stringList = line.split(" ");
for (int j = 0; j < m; j++) {
X[i][j] = Integer.parseInt(stringList[j]);
}
}
// close data file
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
return X;
}
Dataset size parameters n and m are of type static final int and declared outside as well as static final String filePath.
I give you my solution (maybe will be useful for newbies later coming to read this) and ask if it is possible to make it faster in time and/or consuming less memory? I'm interested in perfect micro-optimization, any advice would be great here. In particular I do not like the way the file is opened twice.
Read the file only once and add all lines to an ArraList<String>.
ArrayList grows automatically.
Later process that ArrayList to split the lines.
Further optimisations:
Strimg.split uses a huge regular expression analyzer. Try it with StringTokenizer or your own stringsplit method.
Instead of ArrayList you could avoid overhead by using GrowingIntArray,or GrowingStringArray, these avoid some overhead but are less handy.
speed and mempory usage are contradicting, often you cannot optimize both.
You can save memor by using a one dimesnional array, in java 2d arrays need more space becauseeach column is an object.
access one dim array by X[col + row *rowsize].