How i can get .txt file read line by line - character

I have a file on the SDcard - "file.txt" containing telephone numbers in separate line.
I want to display line first, and then if I press a button, the second line should be displayed in the TextView and the first line should disappear.
I have code that simply reads the contents of txt file and fully insert all rows in TextView:
How should I change this code to the serial output the following line when you press the button????
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,"file.txt");
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
line = br.readLine();
text.append(line);
text.append('\n');
}
}
catch (IOException e) {
}
tv.setText(text);
How should I change this code to the serial output the following line when you press the button????

You could store the content of the file in ArrayList< String> , and then, upon pressing a button, change the text in your TextView to another in the list. Something like:
Reading file and storing in a list:
//make this a class member variable
List<String> numbers = new ArrayList<String>();
while((line = br.readLine()) != null) {
//store each line in our list as separate entry
numbers.add(line);
}
Updating TextView upon button press:
//make this a class member variable
//this is being used to get the line from list
int currentLine = 0;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//set the text
tv.setText(numbers.get(currentLine));
//increment currentLine
currentLine++;
//make sure we don't go beyond the number of lines stored in the list
//so if we reach the last index, we start from the beginning
if (currentLine == numbers.size()) {
currentLine = 0;
}
}
});

Related

Printing to console removes hyperlinks created already

I was trying to create a feature to create hyperlinks in the console while the information is added.
While debugging, I noticed that the first hyperlink is succesfully created, but when the next line is printed to console, the hyperlink dissapears.
The code which I use to create the hyperlinks is:
String hyperLinkText = "test";
myConsole.printToConsole(test);
String myFile = new File("D:/Test/testFile.txt");
URI location = myFile.toURI();
IFile[] files = project.getWorkspace().getRoot().findFilesForLocationURI(location);
HyperlinkInformation hyperlinkInformation = new HyperlinkInformation(myConsole, myConsole.getDocument().get().length(), hyperLinkText.length());
FileHyperlink fileHyperlink = new FileHyperlink(hyperlinkInformation,
files[0], 1);
try {
hyperlinkInformation.getConsole().addHyperlink(fileHyperlink,
fileHyperlink.getOffset(), fileHyperlink.getLength());
} catch (BadLocationException e) {
//
}
The function addHyperlink:
public void addHyperlink(IHyperlink hyperlink, int offset, int length) throws BadLocationException {
IDocument document = getDocument();
ConsoleHyperlinkPosition hyperlinkPosition = new ConsoleHyperlinkPosition(hyperlink, offset, length);
try {
document.addPosition(ConsoleHyperlinkPosition.HYPER_LINK_CATEGORY, hyperlinkPosition);
fConsoleManager.refresh(this);
} catch (BadPositionCategoryException e) {
ConsolePlugin.log(e);
}
}
Is this the normal behaviour or am I missing something?

Eclipse not finding file

I'm having some trouble locating the text file in my code
public static void main(String[] args) {
if (args.length != 2) {
throw new IllegalArgumentException("args is out of range");
}
final String from = args[0];
final String to = args[1];
int errCode = 0; // Unix error handling
// FileReader uses "the default character encoding".
// To specify an encoding, use this code instead:
// new BufferedReader(new InputStreamReader(new
// FileInputStream(fileName), "UTF-8"));
// This "try-with-resource" statement automatically calls file.close()
// just before leaving the try block.
try (BufferedReader file = new BufferedReader(new FileReader("distances.txt"))) { // absolutadressen :C
pathSearch(from, to, file);
} catch (IOException e) {
System.err.println("File not found");
errCode = 1;
} finally {
System.exit(errCode);
}
}
Everytime I run it, it says "File not found". I've tried replacing "distances.txt" with the adress distances.txt is at. distances.txt is also inside the project folder so I don't understand why it's not being found. If i run the code from the terminal, the file can be found by using its adress, but I would like it to work from eclipse. An alternativ is to be able to place this whole package
Here's a pic of the project
Take it out of the package to the src folder, then use the line below to read it:
BufferedReader file = new BufferedReader(new FileReader(getClass().getResource("/distances.txt").getFile()));

java characters upper and lower case

Each character should switch between upper and lower case. My issue is that I cannot get it to work properly. This is what I have so far:
oneLine = br.readLine();
while (oneLine != null){ // Until the line is not empty (will be when you reach End of file)
System.out.println (oneLine); // Print it in screen
bw.write(oneLine); // Write the line in the output file
oneLine = br.readLine(); // read the next line
}
int ch;
while ((ch = br.read()) != -1){
if (Character.isUpperCase(ch)){
Character.toLowerCase(ch);
}
bw.write(ch);
}
Here you go. You had a few problems:
You were never actually storing the result of the character case switch.
You needed to save the line return with each row
I broke out the case switch to make it easier to read
Here's the modified code:
public static void main(String args[]) {
String inputfileName = "input.txt"; // A file with some text in it
String outputfileName = "output.txt"; // File created by this program
String oneLine;
try {
// Open the input file
FileReader fr = new FileReader(inputfileName);
BufferedReader br = new BufferedReader(fr);
// Create the output file
FileWriter fw = new FileWriter(outputfileName);
BufferedWriter bw = new BufferedWriter(fw);
// Read the first line
oneLine = br.readLine();
while (oneLine != null) { // Until the line is not empty (will be when you reach End of file)
String switched = switchCase(oneLine); //switch case
System.out.println(oneLine + " > "+switched); // Print it in screen
bw.write(switched+"\n"); // Write the line in the output file
oneLine = br.readLine(); // read the next line
}
// Close the streams
br.close();
bw.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
public static String switchCase(String string) {
String r = "";
for (char c : string.toCharArray()) {
if (Character.isUpperCase(c)) {
r += Character.toLowerCase(c);
} else {
r += Character.toUpperCase(c);
}
}
return r;
}

Write files from multiple rest requests

I have a rest service written to receive a file and save it.
The problem is that when I receive more than 2 requests, the files are not written only the last request is taken into consideration and written.
Here is my code:
#POST
#RequestMapping(value = "/media/{mediaName}/{mediaType}")
#Produces(MediaType.APPLICATION_OCTET_STREAM)
#ResponseBody
public String updateResourceLocally(#FormDataParam("rawData") InputStream rawData, #PathVariable("mediaName") String mediaName, #PathVariable("mediaType") String mediaType) {
logger.info("Entering updateResourceLocally for " + jobId + "; for media type: " + mediaType);
final String storeDir = "/tmp/test/" + mediaName + ("/");
final String finalExtension = mediaType;
final InputStream finalRawData = rawData;
// new Thread(new Runnable() {
// public void run() {
// writeToFile(finalRawData, storeDir, finalExtension);
// }
// }).start();
writeToFile(finalRawData, storeDir, finalExtension);
// int poolSize = 100;
// ExecutorService executor = Executors.newFixedThreadPool(poolSize);
// executor.execute(new Runnable() {
// #Override
// public void run() {
// writeToFile(rawData, storeDir, finalExtension);
// }
// });
logger.info("File uploaded to : " + storeDir);
return "Success 200";
}
I tried to put the writeToFile into threads, but still no success. Here is what writeToFile does
public synchronized void writeToFile(InputStream rawData,
String uploadedFileLocation, String extension) {
StringBuilder finalFileName = null;
String currentIncrement = "";
String fileName = "raw";
try {
File file = new File(uploadedFileLocation);
if (!file.exists()) {
file.mkdirs();
}
while (true) {
finalFileName = new StringBuilder(fileName);
if (!currentIncrement.equals("")) {
finalFileName.append("_").append(currentIncrement).append(extension);
}
File f = new File(uploadedFileLocation + finalFileName);
if (f.exists()) {
if (currentIncrement.equals("")) {
currentIncrement = "1";
} else {
currentIncrement = (Integer.parseInt(currentIncrement) + 1) + "";
}
} else {
break;
}
}
int read = 0;
byte[] bytes = new byte[1024];
OutputStream out = new FileOutputStream(new File(uploadedFileLocation + finalFileName));
while ((read = rawData.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {
throw new RuntimeException(e.getMessage());
}
}
The writeToFile creates a folder and writes a file, if the file already exists, it appends 1 and then increments the 1 accordingly and writes the file, so I would get raw.zip, raw-1.zip, etc.
I think the inputstream bytes are being lost, am I correct in my assumption?
NOTE: I do not have a UI client, I am using Poster a Firefox extension.
Update: What I am trying to achieve here is very simple
I receive number of requests with files attached
I need to save them. If the mediaName and mediaType are the same, then I need to append something to the filename and save it in the same location
If they are different I do not have a problem
The problem I am facing with the current code is that, when I post multiple time to the same URL, I have file-names created according to what I want, but the file content is not right, they vary depending on when the request came in and only the last POST's request is written properly.
Eg. I have a zip file of size 250MB, when I post 5 time, the 1st four will have random sizes and the 5th will have the complete 250MB, but the previous four should also have the same content.
You must separate the stream copy from the free filename assignation. The stream copy must be done within the calling thread (jersey service). Only the file naming operation must be common to all threads/requests.
Here is your code with a little refactoring :
getNextFilename
This file naming operation must be synchronized to guarantee each call gives a free name. This functions creates an empty file to guarantee the next call to work, because the function relies on file.exists().
public synchronized File getNextFilename(String uploadedFileLocation, String extension)
throws IOException
{
// This function MUST be synchronized to guarantee unicity of files names
// Synchronized functions must be the shortest possible to avoid threads waiting each other.
// No long job such as copying streams here !
String fileName = "raw";
//Create directories (if not already existing)
File dir = new File(uploadedFileLocation);
if (!dir.exists())
dir.mkdirs();
//Search for next free filename (raw.<extension>, else raw_<increment>.<extension>)
int currentIncrement = 0;
String finalFileName = fileName + "." + extension;
File f = new File(uploadedFileLocation + finalFileName);
while (f.exists())
{
currentIncrement++;
finalFileName = fileName + "_" + currentIncrement + "." + extension;
f = new File(uploadedFileLocation + finalFileName);
}
//Creates the file with size 0 in order to physically reserve the file "raw_<n>.extension",
//so the next call to getNextFilename will find it (f.exists) and will return "raw_<n+1>.extension"
f.createNewFile();
//The file exists, let the caller fill it...
return f;
}
writeToFile
Must not be synchronized !
public void writeToFile(InputStream rawData, String uploadedFileLocation, String extension)
throws IOException
{
//(1) Gets next available filename (creates the file with 0 size)
File file = getNextFilename(uploadedFileLocation, extension);
//(2) Copies data from inputStream to file
int read = 0;
byte[] bytes = new byte[1024];
OutputStream out = new FileOutputStream(file);
while ((read = rawData.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
}

Changes made in text file (programatically ) are not reflected back

I have following code. On making changes in the text file when I open the file I can't see any change in fact the text of text file is removed.
private void btnGo_Click(object sender, EventArgs e)
{
string content;
string newword = "Tanu";
string oldword = "Sunrise";
System.IO.StreamReader file =
new System.IO.StreamReader(txtFilePath.Text);
while ((content = file.ReadLine()) != null)
{
if (content == "Project name = Sunrise ")
{
string newtxt = Regex.Replace(content, oldword, newword);
content = content.Replace(content, newtxt);
}
// counter++;
}
file.Close();
using (StreamWriter writer = new StreamWriter(txtFilePath.Text))
{
writer.Write(content);
writer.Close();
Error is in your while loop.
while ((content = file.ReadLine()) != null)
after replacing content with newtxt while is executing again and is trying to read next line in file which is setting content to null and so when you come out of while loop your content is null.
try reading file content into a different variable or use say newtxt itself to write to file.